我正在使用: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);}
});
最佳答案
您还应该根据 this question 设置 MIME 类型是 application/json
。然后 jQuery 将理解答案是一个 json 元素。为此,您需要执行以下操作:
header('Content-Type: application/json');
在打印任何内容之前,在您的 UpdateEditAStudent.php
中。
关于php - 从 JQuery 中读取 'echo json_encode( )' 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6599215/