Copy Code code as follows:
var xmlhttp = null;
function Myajax () {
1. Create XMLHttpRequest Objects
2, the need for IE and other browsers to create this object different ways to write different code
if (window. XMLHttpRequest) {
For FF,MOZILAR,OPERA,SAFARI,IE7,IE8
XMLHTTP = new XMLHttpRequest ();
Fixed some browser bugs
if (Xmlhttp.overridemimetype) {
Xmlhttp.overridemimetype ("Text/xml");
}
else if (window. ActiveXObject) {
For browsers below IE6
var activexname = ["MSXML2. XMLHTTP "," Microsoft.XMLHTTP "," "];
for (var i = 0; i < activexname.length; i++) {
try {
Takes out a control name creation, stops if the creation succeeds, and throws an exception
XMLHTTP = new ActiveXObject (Activexname[i]);
Break
catch (e) {}
}
}
You need to confirm the success of XMLHTTP creation
if (!xmlhttp) {
Alert ("XMLHttpRequest creation failed!");
Return
} else {
alert (XMLHTTP);
}
Registers a callback function. Notice that the registration callback function is not parenthesized and adds the value of the function back to the onreadystatechange
Xmlhttp.onreadystatechange = callback;
Setting up connection Information
The first parameter represents the HTTP request method, which supports all HTTP requests, mainly using GET and post
The second parameter represents the URL address of the request, and the parameter of the Get method request is also Urlkh
The third medium parameter represents an asynchronous or synchronous interaction, and True indicates an asynchronous
Xmlhttp.open ("Get", "servlet/checkusername?username=" + UserName, True);
Sending data representations and server-side interactions
In sync, send this will be done after server-side data comes back
Xmlhttp.send (NULL);
In asynchronous mode, send this sentence complete execution immediately
Post-mode requested code
Xmlhttp.open ("POST", "Servlet/checkusername", true);
Post method requires you to set the HTTP request headers yourself
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Post method to send data
Xmlhttp.send ("username=" +username);
}
callback function
function callback () {
Determining the state of an object is an interactive completion
if (xmlhttp.readystate = = 4) {
To determine if HTTP interaction is successful
if (Xmlhttp.status = = 200) {
Getting data returned by the server side
Get plain text data for server-side output
var responsetext = Xmlhttp.responsetext;
alert (responsetext);
}
}
}