jQuery技术:是否可以将变量值中的$ .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关键字。

      以上就是jQuery教程分享是否可以将变量值中的$ .ajax传递给全局?相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/558393.html

      (0)
      上一篇 2021年1月26日
      下一篇 2021年1月26日

      精彩推荐