Php 正确的阅读方法';echo json_encode()';来自JQuery
我使用的是:echo json_encode($Response);将关联数组发送回JQuery Ajax。每当我尝试读取每个ID键值时,都会得到一个未定义的值。请帮我找出我做错了什么。。。提前谢谢 我的PHP代码:Php 正确的阅读方法';echo json_encode()';来自JQuery,php,jquery,ajax,echo,json,Php,Jquery,Ajax,Echo,Json,我使用的是:echo json_encode($Response);将关联数组发送回JQuery Ajax。每当我尝试读取每个ID键值时,都会得到一个未定义的值。请帮我找出我做错了什么。。。提前谢谢 我的PHP代码: $Stuff = 'Hello world'; $Success = true; $Content = $Stuff; $Response = array('Success' => $Success, 'Content' => $Content); echo jso
$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);}
});
这是一个数组。您可能应该执行alert(data['Content']) 您还应该根据is
application/json
设置mime类型。然后jQuery就会明白答案是json元素。要执行此操作,请执行以下操作:
header('Content-Type: application/json');
在打印任何内容之前,请在
UpdateEditAStudent.php
中定义正确的数据类型或提供正确的标题,如Lumbendil所述
您可以手动将数据类型
定义为json
,因此您的代码如下所示:
$.ajax({
type: "GET",
url: "../pgs/UpdateEditAStudent.php",
data: "FirstName="+ sFirstName ,
dataType: "json",
...etc
您不必向PHP文件添加头,只需使用以下命令:
保持此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);
}
});
做这样的事
$Stuff = 'Hello world';
$Success = true;
$Content = $Stuff;
$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);
Javascriptarrays
with key=>value?@Lumbenil。非常感谢你。与Niklaas建议的在$.ajax数据类型中定义正确的数据类型:“json”相比,您的解决方案的优势是什么?仅仅是UpdateEditAStudent.php
的正确性,因为现在Apache(或任何Web服务器)告诉任何下载给定URL的人该URL是HTML页面(mime类型text/HTML
)而不是真正的mime类型,即application/json
。他询问了JQuery中的编码。您给出了一个来自php的数组示例。他已经做到了。