简体   繁体   中英

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:

$('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:

echo json_encode($_POST);

but when I try to alert the data with 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() . jQuery will try to recognize returned content type, but you need to set correct headers. 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() ):

$.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. Without it, jQuery will check the Content-Type header and apply parser according to it. Suppose if no custom content type headers set, it will return return data as 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); I get "undefined"?

JSON is a regular string which should be parsed on client side. jQuery detects your response as plain text or HTML and does not parse JSON to Javascript object. In case of data being an object, you would get [object Object] in alert window.

I think this should be this way using $.getJSON() :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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