簡體   English   中英

如何在Jquery中解析Json對象

[英]How to parse Json object in Jquery

我對JSON有一點經驗,我現在在網頁上再次使用JSON作為AJAX響應在我的Android應用程序上進行了此操作,我對ajax進行了研究,並找到了使用JSON將數據庫中的數據獲取到的教程,所以我嘗試了但沒有知道如何解析對象。

我的Jquery代碼。

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'functions/json.php',
    success: function(response){
   var json = $.parseJSON(response);
   alert(json.firstname) //where my response is $response['firstname']
},
error: function(data){
   var json = $.parseJSON(data);
   alert(json.error);
}
});

使用php我將jsonArray回顯為json_encode並在此輸出json

{"id":"2","firstname":"john","lastname":"Doe"}

使用谷歌瀏覽器控制台我收到此錯誤

Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)

當函數響應輸出為警報(響應)輸出為

[object Object]

不要解析它。 您已經告訴jQuery:

dataType: "json"

因此, response是已解析的對象,而不是JSON。 只需直接使用它:

$.ajax({
    type: 'GET',
    dataType: 'json',
    url: 'functions/json.php',
    success: function(response){
        alert(response.firstname);
    },
    error: function(data) {
        // `data` will not be JSON
    }
});

另請注意, error回調的第一個參數將不是JSON或錯誤回調中解析JSON的結果。

有關詳細信息,請參見文檔

暫無
暫無

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

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