Application and summary of Ajax technology

Source: Internet
Author: User

Ajax (Asynchronous JavaScript and XML) is a web development model that integrates Java technology, XML, and Javascript. It allows you to build Web applications based on Java technology, this solves the problem of page overloading frequently encountered in Web Development (that is, you can easily obtain server data without page refresh)

The application in this example is based on Java Servlet technology (which can be easily extended to bean). Three files must be created: index. jsp ajaxuse. Java Web. xml.

--------------- Index. jsp file code

<% @ Page contenttype = "text/html; charset = gb2312" %>
<HTML>
<Title> Ajax application </title>
<Head>
<Script language = "JavaScript">
VaR req;
Function senddata (){
VaR idfield = Document. getelementbyid ("userid ");
VaR url = "Servlet/ajaxuse? Id = "+ escape (idfield. value );
Waitmessage ();
If (window. XMLHttpRequest ){
Req = new XMLHttpRequest ();
} Else if (window. activexobject ){
Req = new activexobject ("Microsoft. XMLHTTP ");
}
Req. Open ("get", URL, true );
// Open contains five parameters: (http-method, URL, async, userid, password) the first three are necessary, and the last two are optional.
// ---- Http-method: the communication method of HTTP, such as get or post
// ---- URL: the URL of the server that receives XML data. The ASP or CGI program is usually specified in the URL.
// ---- Async: Boolean ID. for Asynchronous Communication (true), the client does not wait for the server to respond; for Synchronous mode (false), the client will not perform other operations until the server returns a message.
// ---- Userid: User ID, used for Server Authentication
// ---- Password, used for Server Authentication
Req. onreadystatechange = callback;
// If the POST method is used, add the following content:
// ---- Req. setRequestHeader ("Content-Type", "application/X-WWW-form-urlencoded ");
// ---- Req. Send ("ID = OK ");
Req. Send (null );
}
Function callback (){
If (req. readystate = 4 ){
// The readystate attribute in the XMLHTTP object can reflect the progress of the server when processing requests
// ---- 0 the response object has been created, but the XML Document Upload process has not ended.
// ---- 1 the XML file has been loaded
// ---- 2 the XML file has been loaded and is being processed.
// ---- 3 some XML documents have been parsed
// ---- 4 the document has been parsed and the client can accept the returned message
If (req. Status = 200 ){
// Check whether the server response is successfully received
Parsemessage ();
}
}
}
Function parsemessage (){
VaR message = Req. responsexml. getelementsbytagname ("data ");
VaR STR = new array ();
If (message. length> = 1 ){
For (VAR I = 0; I <message. length; I ++ ){
STR [I] = message [I]. firstchild. Data;
}
} Else {
STR [0] = message. length;
}
Mdiv = Document. getelementbyid ("useridmessage ");
Mdiv. innerhtml = "<div>" + STR [0] + "</div> ";
}
Function waitmessage (){
Mdiv = Document. getelementbyid ("useridmessage ");
Mdiv. innerhtml = "<div> Please wait ---- </div> ";
}
</SCRIPT>
</Head>
<Body bgcolor = silver>
<Font size = 2> enter a number and Ajax will obtain the server-side response statically on the page: </font>
<Input type = "text" name = "ID" id = "userid" size = "20">
<Input type = "button" value = "send" onclick = "senddata ()">
<Div id = "useridmessage"> </div>
</Body>
</Html>

--------------- Ajaxuse. Java File Code

Package com. servlet;

Import javax. servlet .*;
Import javax. servlet. http .*;

Public class ajaxuse extends httpservlet {
Private servletcontext context;
Public void Init (servletconfig config) throws servletexception {
This. Context = config. getservletcontext ();
}
Public void doget (httpservletrequest request, httpservletresponse response)
Throws ioexception, servletexception {
String targetid = request. getparameter ("ID ");
Stringbuffer sb = new stringbuffer ("<message> ");
Response. setcontenttype ("text/XML ");
Response. setheader ("cache-control", "No-Cache ");
SB. append ("<DATA> Liaoning </data> <DATA> Shenyang </data> ");
SB. append ("</message> ");
Printwriter out = response. getwriter ();
Out. Write (sb. tostring ());
Out. Close ();
}
}
}

--------------- Web. xml file code

<? XML version = "1.0" encoding = "UTF-8"?>
<! Doctype web-app public "-// Sun Microsystems, Inc. // DTD web application 2.3 //" http://java.sun.com/dtd/web-app_2_3.dtd ">
<Web-app>
<Servlet>
<Servlet-Name> ajaxuse </servlet-Name>
<Servlet-class> com. servlet. ajaxuse </servlet-class>
</Servlet>
<Servlet-mapping>
<Servlet-Name> ajaxuse </servlet-Name>
<URL-pattern>/servlet/ajaxuse </url-pattern>
</Servlet-mapping>
</Web-app>

In this example, a button is used to trigger the client's senddata () method to send data to the server. If you need to send data to the server at a fixed time by default, you can add a timer in JavaScript code: setinterval ("senddata ()", 1000), in milliseconds.

Usage summary:
You may encounter the following problems during use:
1> for pages that use ajax to transmit data, if setinterval () is used for regular transmission and the transmission interval is set to a short value, if you try to click some links on this page, the response is slow;
2> If the amount of data transmitted is large, there will be a little delay when loading and displaying dynamic data. We recommend that you req here. readystate is not equal to 4 (that is, the client has not completed receiving data), for example, adding prompt information such as "loading data;
3> If the data transmitted from the server is in text/XML format, Chinese characters may occur. For example, when the data you send contains Chinese characters, if the data received by the client is still parsed in XML format, no data will be parsed, and no exception is reported. In this case, you need to add an encoding format for the XML format, as shown in <? XML version = "1.0" encoding = "GBK"?>; You can also convert the format of the transmitted data to text/html without any settings. However, parsing the received data on the client may be troublesome. There are two methods: one is to use a string. split () "splits the entire data string according to some specific strings. One is to use a regular expression, such as req. responsetext. match (/<DATA> (. *?) </Data>/g); matches the data contained in <DATA> </data>, but there is a small problem, the matched data still contains the <DATA> </data> tags. In the code that follows, clear the two tags: "str. replace ("<DATA>", ""); Str. replace ("</data> ","");"

Related Article

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.