问题描述
我对AJAX调用非常陌生-在网络上拨了一些教程,但仍然不太成功.
I'm very new to AJAX calls - poked around the web for a few tutorials but still not quite getting successful at it.
输入字段的ID为"idkey".脚本如下:
The input field has an assigned ID of "idkey". The script is as follow:
$(document).on("keyup.autocomplete", "#idkey", function(){
var query = "q=" + $(this).val();
$.ajax({
url: 'api.php',
type: 'GET',
data: query,
dataType: 'json',
success: function(data) {
alert(data);
for (var i=0;i<data.length;i++) {
content = data[i].IDKey;
content += "<br>";
$(content).appendTo("#output");
// updateListing(data[x]);
}
}
});
});
在服务器端,api.php的输出为:
On the server side, the api.php has an output of:
[{"IDKey":"30000001"},{"IDKey":"30000002"},{"IDKey":"30000004"}]
我不确定alert(data)
为什么会返回[object Object], [object Object], [object Object]
.为何会发生这种情况的任何线索?
I am not sure why the alert(data)
would return [object Object], [object Object], [object Object]
. Any clue to why this is happening?
p/s:php文件的标头设置为Content-Type: application/json
.
p/s: The php file has a header set to Content-Type: application/json
.
推荐答案
您的json响应是3个对象组成的数组.这就是您将警报视为对象的原因.
Your json response is an array of 3 objects . That's the reason you are seeing the alert as an object..
尝试alert(data[0].IDKey)
..应该会给您30000001
Try alert(data[0].IDKey)
.. It should give you 30000001
要查看数据,请尝试console.log或将警报放入循环
To see the data try console.log or place the alert inside for loop
for (var i=0;i<data.length;i++) {
alert(data[i].IDKey);
}
$.each(data, function(i, value) {
console.log('Value of '+ i +' is : ' + value);
})
这篇关于Ajax成功函数返回[对象,对象]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!