我有以下JSON数组:
[{"occurences":"1","post_title":"Test 1","ID":"16"},
{"occurences":"1","post_title":"Test 2","ID":"19"},
{"occurences":"1","post_title":"\\u543b\\u60a8\\u7684\\u5c41\\u80a1","ID":"21"}]
我使用这个js来解析和打印它:
success:function(data){
$.each(data, function(i, post){
content = \'\';
content += \'<li>\' + post.post_title + \'</li>\';
});
$(content).appendTo("#search-results");
}
但显示屏上只显示“未定义”,控制台上没有显示错误。
如果您问,这是HTML部分:
<form id="search" action="">
<div class="toolbar">
<h1>Search</h1>
<a href="#" class="back">Back</a>
</div>
<ul class="rounded">
<li><input type="text" name="search-text" placeholder="Search" id="search-text" /></li>
</ul>
<ul class="edgetoedge" id="search-results">
<li class="sep">Results</li>
</ul>
</form>
有什么线索吗?非常感谢!
最合适的回答,由SO网友:Josef Young 整理而成
$.ajax({
url: \'http://mypath/wp-admin/admin-ajax.php\',
data:{
\'action\':\'go_ajax\',
\'fn\':\'spw_autosuggest\',
\'queryString\': $.trim(inputString.val())
},
dataType: \'JSON\',
success:function(data){
// this part is what happens with the JSON data
//console.log(data);
var content = \'\';
var data = $.parseJSON(data);
$.each(data, function(i, post) {
content += \'<li>\' + post.post_title + \'</li>\';
});
$(content).appendTo("#search-results");
},
error: function(errorThrown){
alert(\'error\');
console.log(errorThrown);
}
});
SO网友:Martin Zeitler
为请求设置正确的数据类型是上面的回答中没有考虑的一个重要细节(这会导致jQuery随请求发送一个HTTP Accept标头,并且它也会在成功回调中预期JSON数据):
dataType: \'json\',
success:function(json){
var content = \'\';
jQuery.each(json, function(i, v){
content += \'<li>\' + v.post_title + \'</li>\';
});
/* like this the results won\'t cummulate */
jQuery("#search-results").html(content);
}
也没有考虑将正确的HTTP标头与响应一起发送:
header("content-type: application/json; charset=utf8");
Internet Exploder不喜欢这个标题,但这是另一个故事
(read more).