Copy codeThe Code is as follows:
Var xmlhttp = null;
Function myajax (){
// 1. Create an XMLHttpRequest object
// 2. You need to write different code for setting up this object in IE and other browsers.
If (window. XMLHttpRequest ){
// For FF, Mozilar, Opera, Safari, IE7, and IE8
Xmlhttp = new XMLHttpRequest ();
// Fixed some browser bugs
If (xmlhttp. overrideMimeType ){
Xmlhttp. overrideMimeType ("text/xml ");
}
} Else if (window. ActiveXObject ){
// For browsers under IE6
Var activexName = ["MSXML2.XMLHTTP", "Microsoft. XMLHTTP", ""];
For (var I = 0; I <activexName. length; I ++ ){
Try {
// Retrieve a control name and create it. If it is successfully created, it stops. Otherwise, an exception is thrown.
Xmlhttp = new ActiveXObject (activexName [I]);
Break;
} Catch (e ){}
}
}
// Check whether xmlhttp is created successfully.
If (! Xmlhttp ){
Alert ("XMLHTTPRequest creation failed! ");
Return;
} Else {
Alert (xmlhttp );
}
// Register the callback function. Note that the callback function registration cannot be enclosed by parentheses. If it is added, the function value is returned to onreadystatechange.
Xmlhttp. onreadystatechange = callback;
// Set the connection information
// The first parameter indicates the http request method. It supports all http request methods, mainly using get and post.
// The second parameter indicates the request url. The get request parameter is also in urlKh.
// The third parameter indicates asynchronous or synchronous interaction, and true indicates Asynchronous interaction.
Xmlhttp. open ("GET", "servlet/CheckUserName? UserName = "+ userName, true );
// Send data to indicate interaction with the server
// In synchronous mode, the send statement is executed only after the server data is returned.
Xmlhttp. send (null );
// In asynchronous mode, the send statement is executed immediately.
// POST Request Code
// Xmlhttp. open ("POST", "servlet/CheckUserName", true );
// Set the http request header in POST mode.
// Xmlhttp. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded ");
// Send data in POST Mode
// Xmlhttp. send ("userName =" + userName );
}
// Callback function
Function callback (){
// Determine whether the object state is interactive.
If (xmlhttp. readyState = 4 ){
// Determine whether http interaction is successful
If (xmlhttp. status = 200 ){
// Obtain the data returned by the server
// Obtain the plain text data output by the server
Var responseText = xmlhttp. responseText;
Alert (responseText );
}
}
}