[英]Firefox Extension: multiple requests with XMLHttpRequest. Use Asynchronous or not?
對於第一個Firefox插件,我正在嘗試一些非常簡單的方法,重要的部分是:
步驟1)調用外部API來檢索一些數據。
第2步)使用首次獲取的數據再次調用該API,以獲取更多信息。
現在,我首先使用XMLHttpRequest在同步模式下實現了它,因為我認為需要等待步驟2迫使我這樣做。 對處理該API調用的函數的兩次調用使用XMLHttpRequest並解析了響應。 精細。
然后我遇到了Mozilla開發網絡中的各種文檔,這些文檔鼓勵您在異步模式下使用XMLHttpRequest,因此我嘗試了。
將我的實現基於多個XMLHttpRequests和其他對象,我想到了以下代碼。
我的問題是:這是正確的方法嗎? 我應該回到使用同步模式嗎? 它的工作原理是這樣的,但是它並沒有讓我成為您將要使用的正確AJAX模式...
// first call
var username = foo;
var password = bar;
var startOffset = 0; // initial value
var url = encodeURIComponent('https://theapiurl.com/query=' + startOffset);
doRequest();
function doRequest() {
makeRequest(url, username, password);
}
function makeRequest(url, username, password) {
var http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
alertContents(http_request);
};
http_request.open('GET', url, true, username, password);
http_request.send(null);
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
if (startOffset == 0) {
startOffset = 45; // this value would be extracted from 'http_request'
url = encodeURIComponent('https://theapiurl.com/query=' + startOffset);
// second call, parameter startOffset has changed
doRequest();
} else {
}
} else {
alert('There was a problem with the request.');
}
http_request.onreadystatechange = function fnNull(){};
}
}
您應該始終避免執行同步網絡請求,因為這將阻止GUI起作用,直到獲得響應為止。 僅僅因為網絡對您來說是快速的,您不應該假設它對所有用戶都是快速的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.