The following code summarizes a piece of core Ajax code through a large number of experiments. It is more flexible. Post and get can be used for passing parameters, and text and XML can be returned.
<Script language = "JavaScript">
// JavaScript document
VaR http_request = false;
// Send the request. The first parameter is the destination address, and the second parameter is that the request method has only "get" and "Post"
// The third parameter is the list of parameters to be transferred. key1 = value1 & key2 = value2
// The fourth parameter indicates that the response information type can only be "text" or "XML"
Function send_request (URL, method, Params, responsetype)
{// Initialize, specify the processing function, and send the request Function
Http_request = false;
// Start initializing the XMLHTTPRequest object
If (window. XMLHttpRequest)
{// Mozilla Browser
Http_request = new XMLHttpRequest ();
If (http_request.overridemimetype)
{// Set the mime category
Http_request.overridemimetype ('text/xml ');
}
}
Else if (window. activexobject)
{// IE browser
Try
{
Http_request = new activexobject ("msxml2.xmlhttp ");
}
Catch (E)
{
Try
{
Http_request = new activexobject ("Microsoft. XMLHTTP ");
}
Catch (E)
{}
}
}
If (! Http_request)
{// Exception. An error occurred while creating the object instance.
Window. Alert ("the XMLHTTPRequest object instance cannot be created .");
Return false;
}
Http_request.onreadystatechange = function () {processrequest (responsetype )};
If (Method = "get ")
{
// Determine the request sending method and URL and whether to execute the following code synchronously
Http_request.open (method, URL + "? "+ Params, true );
Http_request.send (null );
}
Else if (Method = "Post ")
{
Http_request.open (method, URL, true );
Http_request.setrequestheader ("Content-Type", "application/X-WWW-form-urlencoded ");
Http_request.send (Params );
}
Else
{
Alert ("invalid method! Method can only be: Get or post ");
}
}
// Function for processing the returned information
Function processrequest (responsetype)
{
If (http_request.readystate = 4)
{// Determine the object status
If (http_request.status = 200)
{// The information has been returned successfully. Start to process the information.
If (responsetype = "text ")
{
Alert (http_request.responsetext );
}
Else if (responsetype = "XML ")
{
Alert (http_request.responsexml );
}
Else
{
Alert ("Invalid Response Information type! Can only be text or XML ");
}
/*
Alert (http_request.responsetext );
*/
}
Else
{// The page is abnormal.
Alert ("the page you requested has an exception. ");
}
}
}
Function usercheck ()
{
Alert ("");
Send_request ('postback. asp ', "Post", "name = arlang", "text ");
Alert ("B ");
}
</SCRIPT>