有人可以向我解释为什么会发生以下情况。首先看下面的代码。尝试通过JSON请求获取数据并保存以供以后使用。
var entities;
//@jsonGetEntities is an url build by asp.net MVC and this works
$.getJSON("@jsonGetEntities", function(getdata) {
entities = getdata;
//I would expect that this is the first alert
alert(entities + "first");
});
//I would expect that this is the second alert
alert(entities + "second");
然而,我期望首先出现的警报是第二个,而entities
实际上是填充的。
在上次提醒entities
未填写。
我似乎无法理解为什么我的json没有保存到var以及为什么稍后调用的警报会被执行?你能给我一个可能的其他解决方案吗?
答案 0 :(得分:3)
答案 1 :(得分:0)
$.getJSON("@jsonGetEntities", function(getdata) {
entities = getdata;
//I would expect that this is the first alert
alert(entities + "first");
setTimeout(function() {
//I would expect that this is the second alert
alert(entities + "second");
},2000); // wait 2 sec.
});