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

Sir*_*rBT 6 php ajax jquery json echo

我正在使用: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);
Run Code Online (Sandbox Code Playgroud) ##

我的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);}
});  
Run Code Online (Sandbox Code Playgroud)

Lum*_*dil 9

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

header('Content-Type: application/json');
Run Code Online (Sandbox Code Playgroud)

在你UpdateEditAStudent.php打印之前的任何东西.


Ant*_*mon 6

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

保持这个PHP代码:

$Stuff = 'Hello world';

$Success = true;
$Content = $Stuff;

$Response = array('Success' => $Success, 'Content' => $Content);
echo json_encode($Response);
Run Code Online (Sandbox Code Playgroud)

而对于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);
    }
});
Run Code Online (Sandbox Code Playgroud)


Ste*_*ger 1

这是一个数组。你可能应该这样做alert(data['Content']);。