Initial use of AJAX

Source: Internet
Author: User

1. Pay attention to the following points for get requests:
1. If you need to initiate multiple requests, you need to create multiple XMLHttpRequest objects.
2. Understand the meanings of open, onreadystatechange, readystate, responsetext, and status attributes and methods in the XMLHTTPRequest object, and the five statuses of the engine: uninitialized, loaded, loaded, interactive, and completed
3. To use Ajax, clear the cache. Otherwise, an inexplicable error may occur. There are two methods:
A. Use the URL to keep up with the timestamp to prevent browser caching, such:
VaR url = "user_validate.jsp? Userid = "+ trim (field. Value) +" & timestampt = "+ new date (). gettime ();
B. Add the clear cache code in user_validate.jsp:
Response. setcontenttype ("text/html ");
Response. setheader ("cache-control", "No-store"); // http1.1
Response. setheader ("Pragma", "No-store"); // http1.0
Response. setdateheader ("expires", 0 );

Determine whether to reuse the Ajax process when adding a user ID:
1. Create an Ajax engine object XMLHttpRequest
2. Call the open method to establish a connection with the Ajax engine, and notify the Ajax engine that the request method is get, the request URL, and the Asynchronous Method.
3. Tell the Ajax engine how to report the result to us after processing is complete. We usually specify a method handle, so Ajax will call the method we specified, in this way, you can obtain the data returned by the Ajax engine (that is, the callback mechanism)
4. Call the send method to send Parameters set in steps 2 and 3 to the Ajax engine.

Ajax code example:
1. servlet code:
Protected void Service (httpservletrequest request, httpservletresponse response)
Throws servletexception, ioexception {
Response. setcontenttype ("text/html; charset = gb18030 ");
String clientid = request. getparameter ("clientid ");
Boolean flag = clientmanager. getinstance (). findclientbyclientid (clientid );
If (FLAG ){
Response. getwriter (). Print ("distributor code already exists ");
}
}
2. Code in JSP script:
Function validateclientid (field ){
If (TRIM (field. Value )! = ""){
VaR XMLHTTP = NULL;
// Indicates that the current browser is not IE, such as ns or Firefox
If (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
} Else if (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
VaR url = "Servlet/clientidvalidateservlet? Clientid = "+ trim (field. Value); // The URL path here is the same as the path in the URL-pattern corresponding to servlet-mapping in Web. xml.
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = function (){
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
If (TRIM (XMLHTTP. responsetext )! = ""){
Document. getelementbyid ("spanclientid"). innerhtml = "<font color = 'red'>" + XMLHTTP. responsetext + "</font>"
} Else {
Document. getelementbyid ("spanclientid"). innerhtml = "";
}
} Else {
Alert ("request failed, error code = [" + XMLHTTP. Status + "]");
}
}
};
XMLHTTP. Send (null );
} Else {
Document. getelementbyid ("spanclientid"). innerhtml = "";
}
}


The above is a GET request. If garbled characters appear
In javascript: parameters in the URL in the open method are reencoded as either encodeuricomponent ("XXXX") or encodeuri ("XXXX ").
Servlet: String username = urldecoder. Decode (request. getxxxx, "UTF-8 ");

Ajax acceptance returns data
Generally, the string returned by Ajax is accepted by the responsetext of the XMLHTTPRequest object. However, if the string is composed of XML files, it is accepted by responsexml,
See selectprovservlet and client_level_chart.jsp in DRP.

Ii. POST request:
If you want to upload files or post content to the server, you must call the setRequestHeader method before sending the method, as shown below:
XMLHttpRequest. setRequestHeader ("Content-Type", "application/X-WWW-form-urlenoded ")
The send parameter is not empty. For example:
Send (name = Value & anothername = othervalue & so = on );


Iii. js and JSON:
VaR o = {"name": "value "}
Both O. Name and O ["name"] can obtain the value of value.
Ajax processes the returned JSON string and converts it to a JS object:
Example: eval ("(" + xhr. responsetext + ")");

Iv. provincial/municipal connections
The arrays. aslist method is used to convert the municipal array into a list. The application is as follows:
Business logic layer:
Public class regionservice {
Private Map <string, list <string> map = new hashmap <string, list <string> ();
Public regionservice (){
String [] C1 = new string [] {"Chengdu", "Luoyang", "guang'an", "Deyang "};
String [] C2 = new string [] {"Haidian", "Changping", "Chaoyang "};
Map. Put ("Sichuan", arrays. aslist (CL ));
Map. Put ("Beijing", arrays. aslist (C2 ));
}
Public list <string> loadprovices (){
Return new arraylist <string> (Map. keyset (); // obtain the province in map by using the kekset method.
}
Public list <string> loadcitys (string province ){
Return map. Get (province); // obtain the city of the province.
}
}
Presentation Layer:
Public class loadprovicesservlet extends httpservlet {
Private Static final long serialversionuid = 1l;
Private iregionservice service = new regionserviceimpl ();
Protected void doget (httpservletrequest request, httpservletresponse response ){
List <string> List = service. loadprovices ();
Stringbuffer S = new stringbuffer ("["); // The string format is changed to the array format.
For (INT I = 0; I <list. Size (); I ++ ){
S. append ("\" "). append (list. Get (I). append ("\"");
If (I <list. Size ()-1)
S. append (",");
S. append ("]");
Response. setcontenttype ("text/html; charset = UTF-8"); // set the returned encoding format, otherwise garbled
Response. getwriter (). println (S. tostring ());
}
}
}
In JSP:
<SCRIPT>
VaR XMLHTTP;
Function createxmlhttprequest (){
// Indicates that the current browser is not IE, such as ns or Firefox
If (window. XMLHttpRequest ){
XMLHTTP = new XMLHttpRequest ();
} Else if (window. activexobject ){
XMLHTTP = new activexobject ("Microsoft. XMLHTTP ");
}
}
Function loadprovice (){
// Alert (document. getelementbyid ("userid"). value );
// Alert (field. value );
If (TRIM (field. Value). length! = 0 ){
// Create the Ajax core object XMLHttpRequest
Createxmlhttprequest ();
VaR url = "Servlet/loadprovicesservlet" + "& time =" + new date (). gettime (); // The URL contains the relative path in XML.
XMLHTTP. Open ("get", URL, true );
XMLHTTP. onreadystatechange = function {
If (XMLHTTP. readystate = 4 ){
If (XMLHTTP. Status = 200 ){
VaR ret = eval ("(" + XMLHTTP. responsetext + ")");
} Else {
Alert ("request failed, error code =" + XMLHTTP. status );
}
}
}
// Send the setting information to the Ajax Engine
XMLHTTP. Send (null );
}
}
Window. onload = loadprovice; // send an Ajax request when loading the page
</SCRIPT>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.