简体   繁体   English

无法读取PHP返回的JSON对象

[英]Cannot read JSON object returned from PHP

I am sending a JSON object to a PHP file, The PHP does some manipulation and returns a JSON string: 我正在将JSON对象发送到PHP文件,PHP进行了一些操作并返回JSON字符串:

$('button#indexOpener').on('click', function() {
    var aUsername = $('input#edUsername').val();    
    var aPassword = $('input#edPassword').val();

    if (($.trim(aUsername) != '') && ($.trim(aPassword) != '')) {
        var str = $("#form_login :input").serializeArray();
        $.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
            alert(data.edUsername); 
        }); 
    }
    else {
        alert('Please insert a valid username and password');
        alert("<?php echo URL; ?>/ajax");   
    }
});

the PHP echoes a JSON object: PHP会回显JSON对象:

echo json_encode($_POST);

but when I try to alert the data with jQuery: 但是当我尝试使用jQuery提醒数据时:

function(data) {
  alert(data.edUsername);   
}

is displaying the message undefined. 显示未定义的消息。 I am sure it is something stupid but I cannot see what I am doing wrong, can you help? 我敢肯定这是愚蠢的,但我看不到自己在做错什么,您能帮忙吗?

I see no dataType set for $.post() . 我没有为$.post()设置dataType。 jQuery will try to recognize returned content type, but you need to set correct headers. jQuery将尝试识别返回的内容类型,但是您需要设置正确的标头。 So, you need to add: 因此,您需要添加:

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

before echo json_encode , or you should set dataType:"json" in JS code (fourth parameter of $.post() ): echo json_encode之前,否则您应该在JS代码中设置dataType:“ json”( $.post()第四个参数):

$.post("<?php echo URL; ?>ajax/checklogin", str, function(data) {
    alert(data.edUsername); 
}, "json");

This way, jQuery will know that the data returned is in JSON format and should be parsed. 这样,jQuery将知道返回的数据为JSON格式,应该对其进行解析。 Without it, jQuery will check the Content-Type header and apply parser according to it. 没有它,jQuery将检查Content-Type标头并根据它应用解析器。 Suppose if no custom content type headers set, it will return return data as HTML. 假设未设置自定义内容类型标头,则它将以HTML返回返回数据。 Actually, that is a usual string. 实际上,这是一个通常的字符串。

If I just alert(data) is returning {"edUsername":"qqq" "edPassword":"qqq"} but if I alert alert(data.edUsername); 如果我只是警报(数据)返回{“ edUsername”:“ qqq”“ edPassword”:“ qqq”},但是如果我警报alert(data.edUsername); I get "undefined"? 我得到“未定义”?

JSON is a regular string which should be parsed on client side. JSON是常规字符串,应在客户端进行解析。 jQuery detects your response as plain text or HTML and does not parse JSON to Javascript object. jQuery将您的响应检测为纯文本或HTML,并且不会将JSON解析为Javascript对象。 In case of data being an object, you would get [object Object] in alert window. 如果数据是对象,则会在警报窗口中显示[object Object]。

I think this should be this way using $.getJSON() : 我认为应该使用$.getJSON()

var str = $("#form_login").serialize();

$.getJSON("<?php echo URL; ?>ajax/checklogin", {data:str}, function(data){
     alert(data.edUsername); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM