[英]async:false deprecated, What's the simple way forward?
浏览器根据Synchronous XMLHttpRequest的whatwg规范发出警告。 从警告中,弃用的原因很明显“用户体验”
我的问题是:
这很有意义,因为有几次需要使用async:false
。 它不需要任何“复杂”的方法,例如数据绑定,Deffering或什至将代码放在.done()
或.fail()
方法中。 (使用Jquery时。)
Firefox发出警告:
不赞成在主线程上使用同步XMLHttpRequest,因为它会对最终用户的体验产生不利影响。 有关更多帮助,请访问http://xhr.spec.whatwg.org/
生成警告的代码段( JQuery )示例:
$.ajax({ url: url, type: "GET", data: {}, async: false, success: function(data) { //Do something }, error: function(xhr, status, error) { //Throw error message } }); //Wait for $.ajax to finish execution the continue ...
同步方式可用于动态加载外部.js文件。 如果使用嵌入式回调,则必须加载3或4个外部模块会使您陷入回调地狱。 相反,您可以在加载html页面时照常进行操作,然后我们不在乎“用户体验”? 使用模块加载器会有帮助吗?
好的,我假设您需要使用它来加载此文件或数据,例如,当用户单击某些内容时,便可以使用。 所以你可以这样做;
var lol = {}; var dataOutSide = null; var xhr = new XMLHttpRequest(); xhr.responseType = 'json'; xhr.open('GET', 'https://api.nasa.gov/planetary/apod?api_key=NNKOjkoul8n1CH18TWA9gwngW1s1SmjESPjNoUFo'); xhr.onload = function (e) { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log(xhr.response); // use this to build if you need show this data when the page is loaded dataOutSide = xhr.response; // use this to if you need show this data anytime after the page is loaded } else { console.error('big fail! :('); } } }; xhr.send(); // and then you put you listeners like clicks inside $(document).ready(function .... $(document).ready(function(){ $('#my-btn').click(function (event){ console.log(dataOutSide); // all stuff $('body > div').append('<img src="'+dataOutSide.url+'" />') }); // when i click my btn show me the image ; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <head> <title></title> </head> <body> <div> <button id="my-btn">show me ! </button> </div> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.