2016-12-05 20 views
0

我從jQuery GET請求中獲取此結果,但它不被視爲對象。jQuery獲取作爲對象無法訪問的數據

[{ 
    "amount": "19323", 
    "image_tag_id": "1", 
    "language_iso": "en", 
    "image_tag": "bla", 
    "image_content_id": "1", 
    "image_id": "1", 
    "last_change": "2010-08-18 09:46:53", 
    "description": "bla presented by a hairy fly", 
    "title": "bla_presented_by_a_hairy_fly", 
    "alt_text": "bla presented by a hairy fly" 
}] 

這是我得到的結果。 我需要在頁面上顯示的金額。 但現在如果我將它作爲「imagecount」結果並詢問imagecount.amountimagecount[0].amount,則它是未定義的。

echo json_encode($results); //gives the results 

$.get('/file.php', imageSearchData, function(imagecount) { 
    $('.imageAmount').html(imagecount[0].amount); 
}); 

調用該文件。

+1

您可能會獲取JSON作爲字符串。如果是這種情況,那麼你需要在JSON字符串上運行'JSON.parse'。 – Enijar

+1

嘗試JSON.parse(imagecount [0] .amount) –

+1

使用'$ .getJSON'來自動爲您解串字符串,或者確保您在PHP的頭文件中設置了正確的'application/json'響應類型。你在PHP代碼中手動構建字符串,即使用串聯?如果是這樣,你應該真的改變這個使用'json_encode()' –

回答

1

正常$.get,得到一個JSON字符串。嘗試使用$.getJSON,它已經解析了json對象。

$.getJSON('/file.php', imageSearchData, function(imagecount) { 
    $('.imageAmount').html(imagecount[0].amount); 
}); 
1

既然你在服務器端的編碼數據,你應該分析它在客戶端使用之前,所以你可能用JSON.parse()$.parseJson()

$.get('/file.php', imageSearchData, function(imagecount) { 
     imagecount = JSON.parse(imagecount); 
     //OR 
     //imagecount = $.parseJson(imagecount); 

     $('.imageAmount').html(imagecount[0].amount); 
}); 

希望這有助於。

1

使用JSON.parse()來解決這個問題。

$.get('/file.php', imageSearchData, function(imagecount) { 
    var imagecountParsed = JSON.parse(imagecount); 
    $('.imageAmount').html(imagecountParsed[0].amount); 
});