Ajax synchronous and asynchronous xmlhttp code analysis

Time:2021-12-31

In Web script programming, asynchronous mode should be used in most cases; Sync mode will suspend the current script engine, so when you use sync mode, you should know what you want. In C + + development, synchronous mode should be the mainstream. If you must use asynchronous mode and callback, you can refer to the article using ixmlhttprequest onreadystatechange from C + +.

The following is the code for obtaining RSS files on the remote host in asynchronous mode. The key is to set a callback function to ixmlhttprequest:: onreadystatechange. To prevent the script from falling back to the console too early, the asyncdone variable is used to detect the current state. Of course, if you use xmlhttp in a web page, you don’t have to be so troublesome — as long as the IE Web page doesn’t close, the callback function won’t exit.

Copy codeThe code is as follows:
var xmlhttp = new ActiveXObject(“MSXML2.XMLHTTP.6.0”);
var url = “https://www.jb51.net/rss.xml”;

var asyncDone = false;

try {
xmlhttp.open(“GET”, url, true);
xmlhttp.onreadystatechange = onReadyStateChange;
xmlhttp.send(null);

// loop so that the program from quiting
while (!asyncDone) {
WScript.Sleep(100);
}

WScript.Echo(xmlhttp.responseText);
} catch (e) {
WScript.Echo(e);
}

function onReadyStateChange() {
WScript.Echo(“readyState: ” + xmlhttp.readyState);
if (xmlhttp.readyState == 4) {
asyncDone = true;
}
}

The code for obtaining remote host resources in synchronous mode is much simpler:

Copy codeThe code is as follows:
var xmlhttp = new ActiveXObject(“MSXML2.XMLHTTP.6.0”);
var url = “https://www.jb51.net/rss.xml”;

try {
xmlhttp.open(“GET”, url, false);
xmlhttp.send(null);
WScript.Echo(xmlhttp.responseText);
} catch (e) {
WScript.Echo(e);
}

However, if the synchronization mode is used in ie, because there is no callback mechanism and ie does not support script thread opening, the script will be suspended until xmlhttp returns. Note that the IE interface itself will be suspended.

Synchronous or asynchronous, specific problems need to be analyzed in detail.

Recommended Today

Redis featured Q & A

Redis data type type brief introduction characteristic scene String (string) Binary security It can contain any data, such as JPG pictures or serialized objects. One key can store up to 512M It can be used to do the simplest data. It can cache a simple string or a JSON format string. The implementation of redis […]