簡體   English   中英

如何使用jQuery讀取JSON響應

[英]How to read JSON response with jQuery

我正在嘗試使用jQuery讀取響應,但我不知道它如何與響應一起工作。

在此處查看帶有js post + response的小示例代碼:

$.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');
    }   
});

響應是:

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

現在我想要的是alert online

有人可以告訴我我在這方面缺少什么嗎?


當我刪除dataType:“ json”時,這工作正常

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

由於dataType設置為json,因此無需解析響應,該方法將解析對json的響應,並將其傳遞給處理程序

只是

alert(data.status)

例如:

$.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

不確定那里的解析方法。 由於您使用的是jQuery,請嘗試:

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

由於您將dataType定義為json,因此您無需解析它,它將為您轉換為object,所以只需執行以下操作:

$.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');
    }   
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM