简体   繁体   中英

How to read JSON response with jQuery

I am trying to read response with jQuery and I have no idea how it works with response.

See the small example code with js post + response here:

$.ajax({
    url: "http://localhost/ajaxpost/ajax.php",
    type: "post",   
    data: "action=check&uid=1",
    dataType: "json",
    success: function(data){
        $("#result").html('submitted successfully');
        response = JSON.parse(data);
        status = response.status;
        alert(status); 
    },
    error:function(){
        $("#result").html('there is error while submit');
    }   
});

Response is:

{"first":"John","last":"Heyden","uid":"1","token":"10","value":"100000","friends":"23","country":"australia","status":"online"}

Now what I want in this is to alert online

Can someone tell me what I am missing in this?


When I remove dataType: "json", this works fine

success: function(data){
    $("#result").html('submitted successfully');
    var r = jQuery.parseJSON(data);
    alert(r.status);

There is no need to parse response as the dataType is set as json, the method will parse the response to json ans will pass it to the handler

just

alert(data.status)

Ex:

$.ajax({
    url: "http://localhost/ajaxpost/ajax.php",
    type: "post",   
    data: "action=check&uid=1",
    dataType: "json",
    success: function(data){
        $("#result").html('submitted successfully');
        status = data.status;
        alert(status); 
    },
    error:function(){
        $("#result").html('there is error while submit');
    }   
});

做就是了

alert(data.status);   // online

Not sure about your parsing method there. Since you're using jQuery, try:

var r = jQuery.parseJSON(data);
alert(r.status);

Since you defined the dataType as json you don't need to parse it, it will be converted to object for you, so just do:

$.ajax({
    url: "http://localhost/ajaxpost/ajax.php",
    type: "post",   
    data: "action=check&uid=1",
    dataType: "json",
    success: function(data){
        $("#result").html('submitted successfully');
        //Don't need this line 
        //response = JSON.parse(data);
       //you called the object data, so use it
        status = data.status;
        alert(status); 
    },
    error:function(){
        $("#result").html('there is error while submit');
    }   
});

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