0
在下面的簡單代碼片段中,我從一個php頁面獲取JSON響應,然後嘗試迭代它並警告每個JSON對象上的名稱字段。但它不警告任何事情。使用jQuery迭代從webservice接收的JSON
<html>
<head>
<title>AJAX DB</title>
</head>
<body>
Name: <input type="text" id="name">
<input type="submit" id="name-submit">
<div id="formatted-data"></div>
<div id="name-data"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script >
$('input#name-submit').on('click',function(){
var name = $('input#name').val();
if($.trim(name) != ''){
$.post('appservice.php', {search_key: 'users_search', search_value: name}, function(data){
//$('div#name-data').text(search_data);
$.each(data, function(i, obj) {
alert(obj.name);
});
});
}
});
</script>
</body>
</html>
樣品JSON
[
{
"id": 18927441,
"id_str": "18927441",
"name": "IGN",
"screen_name": "IGN",
"location": "San Francisco, CA"
}
]
如果你'console.log(data)',它是一個'string'還是'object'?如果它是一個字符串,那麼你需要使用'data = JSON.parse(data);'將它從json轉換爲對象。 – fuyushimoya
非常感謝!不能相信我錯過了這樣一個基本點。 你能解釋爲什麼它是這樣嗎?我只是在一個在線的JSON解析器中複製粘貼響應,並檢測到回顯出的字符串是有效的JSON。所以我認爲這已經是一個JSON對象。 – amin365
因爲您沒有將'dataType'傳遞給[.post](http://api.jquery.com/jQuery.post/),所以jquery會根據返回對象來猜測它,這將基於您的返回信息PHP,它似乎jQuery的猜測它是'文本',所以它沒有爲你解析它,而是它給你的原始內容。如果你將'json'作爲第四參數傳遞,情況就會改變。 – fuyushimoya