是否可以将变量值中的$ .ajax传递给全局?

有没有办法将测试值从ajax函数传递给全局?

$('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

这里有两个问题:

在成功处理程序中,您将使用var关键字重新定义test 。 现在使用一个名为test的新变量,该变量的范围仅限于您的成功处理程序。

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

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

对于这个简单的示例,通过将async属性设置为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; }); 

设置test的值时,不要在ajax回调中使用var关键字。