Ajax synchronization: req. open ('get', url, false );
Instance:
Js Method
Var g_success = false; // global variable
Function getUser (username ){
If ("" = username ){
Alert ("login name cannot be blank! ");
Return;
}
G_success = false;
Var url = "<% = path %>/basicdata/gyshtyCheckUsername. do? Mode = getUser & username = "+ encodeURI (username ));
If (window. XMLHttpRequest ){
Req = new XMLHttpRequest ();
} Elseif (window. ActiveXObject ){
Req = new ActiveXObject ("Microsoft. XMLHTTP ");
}
If (req ){
Req. open ('get', url, false); // synchronous
Req. setRequestHeader ("Content-Length", username. length );
Req. setRequestHeader ("CONTENT-TYPE", "application/x-www-form-urlencoded ");
Req. send ("username =" + encodeURI (username )));
If (req. readyState = 4 ){
If (req. status = 200 ){
Result = req. responseText;
If ('no. '= result ){
Alert ("the login name does not exist! ");
Document. getElementById ("username"). value = "";
Document. forms [0]. username. focus ();
} Else {
G_success = true;
}
}
}
}
}
Ii. Background Service
String username = request. getParameter ("username ");
Users users = gyshtyService. findUsersByUsername (username );
String jsonStr = "no ";
If (users! = Null ){
JsonStr = users. getUsername ();
} Else {
JsonStr = "no .";
}
Response. setContentType ("text/xml; charset = GBK ");
Response. setHeader ("Cache-control", "no-cache ");
Response. getWriter (). print (jsonStr );
Returnnull;
Ajax asynchronous: req. open ('get', url, true );
Instance:
I. js method
Function getNext (){
If (window. XMLHttpRequest ){
Req = new XMLHttpRequest ();
} Elseif (window. ActiveXObject ){
Req = new ActiveXObject ("Microsoft. XMLHTTP ");
}
If (req ){
Var url = "------";
Req. open ("GET", url, true );
Req. onreadystatechange = completeGetNext; // callback function
Req. send (null );
}
}
Function completeGetNext (){
If (req. readyState = 1 ){
Document. getElementById ("loadspan"). innerHTML =
" & nbsp; <font color = red> loading data. Please wait... </font> ";
}
If (req. readyState = 4 ){
If (req. status = 200 ){
// After obtaining the result, start ......
ParseMessageNext ();
}
}
}
Ii. Background Service
Response. setContentType ("text/xml; charset = GBK ");
Response. setHeader ("Cache-control", "no-cache ");
String xml = "<? Xml version = \ "1.0 \" encoding = \ "GBK \"?> ";
/*
Interaction with databases and business logic
*/
Response. getWriter (). write (xml + str );
Summary: callback functions can be defined when asynchronous (true) is used. When synchronous (false) is used, callback functions cannot define another callback function name. I do not know the reason. I hope you can tell me the reason.
Note: The above code is code that has implemented functions in development.