2016-12-05 50 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); 
});