从JQuery读取’echo json_encode()’的正确方法

我正在使用:echo json_encode($ Response); 将关联数组发送回JQuery Ajax。 每当我尝试读取每个ID键值时,我都会得到一个未定义的值。 请帮我弄清楚我做错了什么……提前谢谢

我的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);} }); 

你应该设置mime类型,根据这个问题是application/json 。 然后jQuery会理解答案是json元素。 为此,您需要执行以下操作:

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

在打印任何内容之前,在UpdateEditAStudent.php

您不必向PHP文件添加标头,只需使用此Jquery parseJSON函数 :

保持这个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); } }); 

您需要定义正确的dataType或提供正确的标头,如Lumbendil所述。

您可以手动将dataType定义为json ,因此您的代码如下所示:

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

这是一个arrays。 你应该做警报(data [‘Content’]);.

做这样的事

 $Stuff = 'Hello world'; $Success = true; $Content = $Stuff; $Response = array('Success' => $Success, 'Content' => $Content); echo json_encode($Response);