Mar*_*rco 3 javascript ajax jquery json
我在函数中使用AJAX调用以这种方式从服务器检索一些数据:
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");}
});
}
Run Code Online (Sandbox Code Playgroud)
我正确地得到了JSON数组:
[
{
"policyName": "policy1"
},
{
"policyName": "policy2"
},
{
"policyName": "policy3"
}
]
Run Code Online (Sandbox Code Playgroud)
该函数返回此JSON数组.但是当我调用函数getPolicies()时,我只得到一个空的JSON对象{}.具体来说,如果我尝试
var policies = getPolicies();
console.log(policies[1].policyName);
Run Code Online (Sandbox Code Playgroud)
我明白了:
Uncaught TypeError: Cannot read property 'policyName' of undefined
Run Code Online (Sandbox Code Playgroud)
那么,即使我正确获取JSON数组,该函数又有可能返回一个空对象吗?!谢谢...
即使AJAX请求是同步的*),return语句仍然只从成功处理程序返回.尝试这样的事情:
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;
}
Run Code Online (Sandbox Code Playgroud)
但总的来说,将AJAX调用同步化是不好的做法.相反,您可以从成功处理程序中更好地调用必要的功能.那也可以是另一个功能.例如,您可以声明
function processPolicies(policies)
{
console.log(policies[1].policyName);
}
Run Code Online (Sandbox Code Playgroud)
你的调用处理程序看起来像这样(:
$.ajax({
async: true, // just let it run,
type: "GET",
url: "http://localhost:8080/getPolicies",
contentType: "application/json",
dataType: "json",
success: function(jsonList) {
processPolicies(jsonList);
},
...
Run Code Online (Sandbox Code Playgroud)
*)第一个A even代表异步.但另一方面,X代表XML,所以你在这里所做的事实际上应该被调用JaJ而不是AJAX.;)
| 归档时间: |
|
| 查看次数: |
5551 次 |
| 最近记录: |