繁体   English   中英

无法将getJSON中的信息保存到var中

[英]Can't save information from getJSON into var

任何人都可以向我解释为什么会发生以下情况。 首先看下面的代码。 尝试通过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以及为什么稍后调用的警报会被执行? 你能给我一个可能的其他解决方案吗?

那是因为getJSON()异步的

一个警报位于getJSON的成功回调中,一旦服务器返回,它就会异步执行。

但是, 第二个警报在触发AJAX请求后立即运行(通过getJSON()

 $.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.
        });            

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM