2017-04-24 108 views
0

遇到以下代碼時遇到問題,它會獲取我想要的數據,但它不會附加到div #playercontent,而會在運行時出現在控制檯中。將AJAX響應數據添加到Div

使用PHP,Slim,HTML,JSON。清除它。

$(document).ready(function(){ 


$.ajax({ 
type: 'GET', 
dataType: "json", 
url: "db.php/players", 
success: showResponse, 
error: showError 
}); 

}); 




console.debug("error"); 

function showResponse(responseData){ 

    $("#get1").click(function getPlayers(responseData) { 
    console.log('Image is clicked'); 
    console.log(responseData); 
    $.each(responseData.player, function(index, player){ 
     console.log(' is '); 
     $("#playercontent").append(" </br>Player Position:" +player.PlayerPosition+"</br> Full Name:" +player.PlayerName+ " "+player.PlayerLastName+" </br>Team Name:" +player.TeamName); 
      // $("#playercontent").append("</li>"); 
     console.log('Data should output'); 
    }); 
    }); 

console.log(responseData); 
    } 
    console.debug("hello"); 

function showError(){ 
alert("Sorry, but something went wrong. Fix it!!!!") 
} 
+2

請標籤沒有垃圾郵件。你的問題既不與'Slim'也不與'PHP'相關。 –

+0

感謝您的幫助mate @MarcinOrlowski –

+0

嘗試在'$(document).ready(function(){...}'內移動函數'showResponse'。我們需要確保'playercontent'元素存在於函數showResponse '被定義。 – alfredo

回答

0

將數據追加到#playercontent DIV的代碼是一個onclick事件處理您的Ajax請求的成功處理程序內的範圍內。即它不會運行,因爲點擊將永遠不會發生,因爲您處於成功回調中。嘗試移動遍歷onclick處理函數以外的responseData的代碼,以使其直接位於showResponse函數中。

而且console.debug("error");console.debug("hello");消息將顯示每一個頁面請求和.ajax調用發生之前...