About how to obtain data asynchronously in Microsoft. XMLHTTP or Ajax

Source: Internet
Author: User

I believe I am familiar with the following code.

Function getdata (URL, OBJ)

{
VaR XH;
XH = new activexobject ("Microsoft. XMLHTTP ");
XH. onreadystatechange = function (){
If (XH. readystate = 4)
{
If (XH. Status = 200 ){
Return XH. responsetext;
}
Else {
Return '';
}
}
}
XH. Open ("get", URL + "? Direct = wk2d & D = "+ obj. Value, false );
XH. Send ();
}

However, no matter how you adjust it, the Ajax or XMLHTTP object is used to asynchronously obtain data, we will find that the getdata ("AA. ASP ", object1), it is found that the returned value is always undefined.

This is a problem caused by asynchronous data retrieval. The getdata () function is called in the program. After XH sends the send command, the program does not block the process until the result is returned, instead, the next content in the main program will be executed immediately. At this time, if the main program wants to use the getdata return value, it is probably undefined, at this time, the XH object may still be sending requests and waiting for responses, and the returned value of getdata cannot be provided in time.

So how can we solve this problem? You can find a way to block the program until the returned value is obtained after the getdata function is executed in the main program. The modified code is as follows:

VaR data;
VaR got;
Function getdateurl (URL, OBJ)

{
VaR XH;
Got = false;
XH = new activexobject ("Microsoft. XMLHTTP ");
XH. onreadystatechange = function (){
If (XH. readystate = 4)
{
If (XH. Status = 200 ){
Data = XH. responsetext;
Got = true;
}
Else {
Data = '';
Got = true;
}
}
}
XH. Open ("get", URL + "? Direct = wk2d & D = "+ obj. Value, false );
XH. Send ();
 
}

Blocking content is added to the JS main program:
Getdata ("AAA. asp", object );
While (! Got ){
; // Here the program can be blocked until the got is true, which means the data is obtained.

}
Value = data;

Hope to be useful.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.