AJAX-响应数据不会保存到全球范围有多大? [英] AJAX- response data not saved to global scope?

查看:119
本文介绍了AJAX-响应数据不会保存到全球范围有多大?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的如下行不存储变量到全球范围问题:

I am having the issue of my below shown lines not storing the variable into the global scope:

var somedata;

$.ajax({
    cache: false,
    url: verification_url,
    success: function(data){
        somedata = data;
    }
});

alert(somedata); // Undefined

我是什么做错了吗?我是否需要包装成一个单独的函数或者是什么呢?

What am I doing wrong? Do I need to wrap this into a separate function or what?

推荐答案

警报() code从 $响应之前运行阿贾克斯被接收。

The alert() code runs before the response from $.ajax is received.

这就是为什么它是未定义

var somedata;

$.ajax({
    cache: false,
    url: verification_url,
    success: function(data){
        somedata = data;

        alert( somedata );   // 2. this will occur after the response is received
    }
});

alert(somedata); // 1. this will occur first

在这里你可以看到,警报发生乱序。默认情况下AJAX请求不运行并不prevent随后code。

Here you can see that the alerts happen out of order. By default an AJAX request does not prevent subsequent code from running.

这是有一个的回调的方法的全部目的。它是不是依靠同步执行一个被调用在适当的时间的方法,

That's the entire purpose of having a callback method. It is a method that gets called at the appropriate time, instead of relying on synchronous execution.

这篇关于AJAX-响应数据不会保存到全球范围有多大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆