In the past two days, I happened to see someone asking about the Ajax return value. Solve this problem by the way
Let's take a look at the following code:
<HTML>
<Head>
<Title> Ajax test </title>
<SCRIPT>
// Generate an xhr object (compatible with various browsers)
Function createxhr ()
{
VaR xhr;
Try
{
Xhr = new activexobject ("msxml2.xmlhttp ");
}
Catch (E)
{
Try
{
Xhr = new activexobject ("Microsoft. XMLHTTP ");
}
Catch (E)
{
Xhr = false;
}
}
If (! Xhr & typeof XMLHttpRequest! = 'Undefined') xhr = new XMLHttpRequest ();
Return xhr;
}
// Obtain the Ajax value to be displayed (IE)
Function ieshow (geturl)
{
VaR xhr;
Xhr = createxhr ();
VaR returnstr = '';
Xhr. Open ("get", geturl );
Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4 & xhr. Status = 200)
Returnstr = xhr. responsetext;
}
Xhr. Send (null); // alert ('');
Return returnstr;
}
// Display characters in the specified Block
Function showstr (STR)
{
Document. getelementbyid ('show'). innerhtml = STR;
}
// Display the Ajax value (IE) on the webpage)
Function ieenableshow (geturl)
{
VaR STR = ieshow (geturl );
Showstr (STR );
}
// Compatible with FF IE
Function ffieshow (geturl, funname)
{
VaR xhr;
Xhr = createxhr ();
VaR returnstr = '';
Xhr. Open ("get", geturl );
Xhr. onreadystatechange = function ()
{
If (xhr. readystate = 4 & xhr. Status = 200)
Funname (xhr. responsetext );
}
Xhr. Send (null );
}
</SCRIPT>
</Head>
<Body>
<Input type = 'button 'value = 'ie display result 'onclick = 'ieenableshow ("ajaxshow. php",); '>
<Input type = 'button 'value = 'Firefox ie All show results 'onclick = 'ffieshow ("ajaxshow. php", showstr);'>
<Div id = 'show'> </div>
</Body>
</Html>
Content of the 'ajaxshow. php' File
<? PHP
Echo '1, 2, 3, 4 ';
?>
I use PHP. If you use other languages, you can modify it by yourself. Simply print the strings '1, 2, 3, 4 'on the webpage '.
From the code above, we can see that IE can use return to get the value. But Firefox cannot. You can only process a function when readystate = 4 & status = 200. This function should be passed as a parameter to the function. There is a strange phenomenon that if you remove the comments of the red line, Firefox can get the value again. It is estimated that there is a delay in using Ajax in Firefox.