Javascript JSON AJAX-返回空对象
我在函数中使用AJAX调用从服务器检索一些数据,方法如下:Javascript JSON AJAX-返回空对象,javascript,jquery,ajax,json,Javascript,Jquery,Ajax,Json,我在函数中使用AJAX调用从服务器检索一些数据,方法如下: getPolicies: function() { $.ajax({ async: false, // wait for response type: "GET", url: "http://localhost:8080/getPolicies", contentType: "application/json", dataType: "json", success: function(
getPolicies: function() {
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
return jsonList;
},
failure: function(err) {console.log("Error");}
});
}
我正确地获得了JSON数组:
[
{
"policyName": "policy1"
},
{
"policyName": "policy2"
},
{
"policyName": "policy3"
}
]
此JSON数组由函数返回。
但是当我调用函数getPolicys()时,我只得到一个空的JSON对象{}
。具体来说,如果我尝试
var policies = getPolicies();
console.log(policies[1].policyName);
我明白了:
Uncaught TypeError: Cannot read property 'policyName' of undefined
那么,即使我正确地获取了JSON数组,该函数返回一个空对象,这怎么可能呢?!
谢谢…即使AJAX请求是同步的*),返回语句仍然只从成功处理程序返回。试着这样做:
getPolicies: function() {
// Declare variable here
var resultList = null;
$.ajax({
async: false, // wait for response
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
for(var i in jsonList) {
console.dir(jsonList[i].policyName);
}
// Set the variable in the scope of getPolicies.
resultList = jsonList;
},
failure: function(err) {console.log("Error");}
});
// This one actually returns getPolicies
return resultList;
}
但一般来说,使AJAX调用同步被认为是不好的做法。相反,您可以更好地从成功处理程序调用必要的功能。这也可能是另一个功能。例如,您可以声明
function processPolicies(policies)
{
console.log(policies[1].policyName);
}
您的呼叫处理程序可以如下所示(:
*)第一个A甚至代表异步。但另一方面,X代表XML,因此您在这里所做的实际上应该称为
JaJ
,而不是AJAX
) 仅供参考,您不应该使用async
false。从API:到jQuery1.8,不推荐在jqXHR($.Deferred)中使用async:false;您必须使用success/error/complete回调选项,而不是jqXHR对象的相应方法,如jqXHR.done()或不推荐使用的jqXHR.success()。
是的,实际上它解决了或多或少相同的问题。。。对不起,我以前没收到!
$.ajax({
async: true, // just let it run,
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
processPolicies(jsonList);
},
...