通过$ .ajax内部变量值传递给全局? [英] passible to pass $.ajax inside variable value to global?

查看:297
本文介绍了通过$ .ajax内部变量值传递给全局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将测试值从ajax函数传递到全局?

Is there a way to pass the test value from ajax function to global?

$('button').on('click', 'loader', function(){
    $.ajax({
          url: 'www.myweb.com/string/index.html',
          type: 'get',
          dataType: 'html',
           success: function(data){ 
             var test = true;
           },
            error: function(data){
              var test = false;

           }
});

var test; 

我的console.log显示undefined

my console.log shows undefined

推荐答案

这里有两个问题:

在成功处理程序中,您正在使用var关键字重新定义test.现在,这使用了一个名为test的新变量,该变量仅适用于您的成功处理程序.

Inside your success handler, you are redefining test with the var keyword. This is now using a new variable named test that is scoped for just your success handler.

删除var关键字.然后它将在外部作用域中寻找一个名为test的变量,逐渐向外搜索,直到找到一个名为test的变量,或者找不到一个变量,在这种情况下它将创建一个附加到window的新变量.

Remove the var keyword. Then it will look for a variable named test in the outer scope, searching progressively outward until it either finds a variable named test, or fails to find one in which case it will create a new variable attached to window.

您的第二个问题是,默认情况下ajax是异步的.这意味着,直到所有后续代码完成运行之前,它不会调用test = true.如果要在ajax调用后立即检查test的值,则它将为undefined,因为尚未调用done.

Your second problem is that ajax is asynchronous by default. That means it would not be calling test = true until all of the subsequent code has finished running. If you are examining the value of test immediately after the ajax call, then it will be undefined because the done hasn't been called yet.

对于这个简单的示例,通过将async属性设置为false,使呼叫同步.

For this simple example, make the call synchronous, by setting the async property to false.

// Do you want to use the text within this scope?
// If not, remove this declaration, and then it really will be
// window.test
var test;

$('button').on('click', 'loader', function(){
    $.ajax({
          url: 'www.myweb.com/string/index.html',
          type: 'get',
          async: false,
          dataType: 'html'
}).done(function() {
     test = true;
}).fail(function() {
    test = false;
});

这篇关于通过$ .ajax内部变量值传递给全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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