[英]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.