2011-07-06 26 views
6

我正在使用:echo json_encode($ Response);將關聯數組發送回JQuery Ajax。每當我嘗試讀取每個ID鍵值時,我都會得到一個未定義的值。請幫我找出我在做什麼錯了...在此先感謝正確的方式來閱讀從JQuery echo'json_encode()'

我的PHP代碼:

$Stuff = 'Hello world'; 

$Success = true; 
$Content = $Stuff; 

$Response = array('Success' => $Success, 'Content' => $Content); 
echo json_encode($Response); 
# #

我的JS代碼:

var sFirstName  = $('#student_first_name').attr('value'); 

$.ajax({ 
    type: "GET", 
    url: "../pgs/UpdateEditAStudent.php", 
    data: "FirstName="+ sFirstName , 

    //The below code will give me: {"Success":true,"Content":"Hello world"} 
    success: function(data){$("#Ajax_response").html(data);} 

    //The popup window will show me "Undefined" 
    //and: {"Success":true,"Content":"Hello world"} 
    success: function(data){$("#Ajax_response").html(data); alert(data.Content);} 
}); 

回答

1

這是數組。你應該做alert(data ['Content']);.

+0

的Javascript'與關鍵=>值arrays'? – Niklas

9

您應該設置MIME類型以及,根據this questionapplication/json。然後jQuery會明白答案是一個json元素。要做到這一點,你會做到以下幾點:

header('Content-Type: application/json'); 

在你UpdateEditAStudent.php打印任何東西之前。

+0

@Lumbenil。非常感謝你。按照Niklaas的建議,與定義$ .ajax dataType中的正確數據類型相比,您的解決方案的優勢是什麼:「json」? – SirBT

+0

由於現在Apache(或任何網絡服務器)正告訴任何下載給定的URL是HTML頁面(mime類型爲「text/html」)而不是真實的MIME類型的'UpdateEditAStudent.php',那就是'application/json'。 – Lumbendil

2

您需要定義正確的dataType或提供正確的標題,正如Lumbendil所述。

您可以手動定義dataTypejson,所以你的代碼看起來像:

$.ajax({ 
    type: "GET", 
    url: "../pgs/UpdateEditAStudent.php", 
    data: "FirstName="+ sFirstName , 
    dataType: "json", 
    ...etc 
+0

謝謝你,這對我很好!太棒了! :-D – SirBT

4

您不必到頭添加到PHP文件,只需使用該Jquery parseJSON function

保持這個PHP代碼,因爲它是:

$Stuff = 'Hello world'; 

$Success = true; 
$Content = $Stuff; 

$Response = array('Success' => $Success, 'Content' => $Content); 
echo json_encode($Response); 

而對於JS:

$.ajax({ 
    type: "GET", 
    url: "../pgs/UpdateEditAStudent.php", 
    data: "FirstName="+ $('#student_first_name').val(), 

    success: function(data){ 
     // Here is the tip 
     var data = $.parseJSON(data); 

     alert(data.Content); 
    } 
}); 
0

做這樣的事情

$Stuff = 'Hello world'; 

$Success = true; 
$Content = $Stuff; 

$Response = array('Success' => $Success, 'Content' => $Content); 
echo json_encode($Response); 
+0

他問起JQuery的編碼問題。你給了一個從PHP數組的例子。他已經做到了。 –

+0

bot 91203沒有回覆 – asdasd

相關問題