Ajax Implementation page Local Refresh sample code summary

Source: Internet
Author: User

Automatic refresh of the Web site has been a common occurrence, such as real-time news information, stock information, etc., need to constantly get the latest information. In the traditional way of web implementation, want to achieve similar effect, must carry out the whole page refresh, in the network speed under certain restrictions, this because of a local change affects the whole page of the processing method appears to outweigh the gains. Ajax technology to the emergence of a good solution to this problem, the use of AJAX technology to achieve local Web page refresh, only to update the specified data, do not update other data.
Now create an instance to demonstrate the automatic refresh feature of the Web page, which simulates the display caption of the train ticket hall.
1, server-side code


The server-side code of this instance is simpler, producing a random number and returning it to the client in the form of an XML file. Open Notepad and enter the following code:

The code is as follows Copy Code
<%@ page contenttype= "text/html; charset=gb2312 "%>
<%
Response.setcontenttype ("Text/xml; Charset=utf-8 ")//set the format and character set of output information
Response.setheader ("Cache-control", "No-cache");
Out.println ("<response>");
for (int i=0;i<2;i++) {
Out.println ("<name>" + (int) (Math.random () *10) + "</name>");
Out.println ("<count>" + (int) (Math.random () *100) + "</count>");
}
Out.println ("</response>");
Out.close ();
%>

Save the above code, named Auto.jsp. In this file, the math class in the Java.lang package is used to produce a random number.

2, client code


This instance client code mainly uses the number returned by the server side to specify the display style. Open Notepad and enter the following code:

The code is as follows Copy Code

<%@ page language= "java" import= "java.util.*" pageencoding= "GBK"%>
<meta http-equiv=content-type content= "text/html; charset=gb2312 ">
<script language= "JavaScript" >


var xmlhttpreq;
Creating XMLHttpRequest Objects
function Createxmlhttprequest () {
if (window. XMLHttpRequest) {//mozilla browser
Xmlhttpreq = new XMLHttpRequest ();
}
else if (window. ActiveXObject) {//IE browser
try {
Xmlhttpreq = new ActiveXObject ("Msxml2.xmlhttp");
catch (e) {
try {
Xmlhttpreq = new ActiveXObject ("Microsoft.XMLHTTP");
catch (e) {}
}
}
}
Send Request function
function SendRequest () {
Createxmlhttprequest ();
var url = "Auto.jsp";
Xmlhttpreq.open ("Get", url, True);
Xmlhttpreq.onreadystatechange = processresponse;//Specify response function
Xmlhttpreq.send (NULL); Send Request
}
Processing return information functions
function ProcessResponse () {
if (xmlhttpreq.readystate = = 4) {//Judge object state
if (Xmlhttpreq.status = = 200) {//information has been successfully returned to start processing information
Displayhot ();
SetTimeout ("SendRequest ()", 1000);
} else {//page is not normal
Window.alert ("The page you requested has an exception.) ");
}
}
}
function Displayhot () {
var name = XMLHttpReq.responseXML.getElementsByTagName ("name") [0].firstchild.nodevalue;
var count = XMLHttpReq.responseXML.getElementsByTagName ("Count") [0].firstchild.nodevalue;

document.getElementById ("Cheh"). InnerHTML = "T" +name+ "secondary Train";
document.getElementById ("Price"). InnerHTML = count+ "Yuan";
}


</script>
<body onload =sendrequest () >
<table style= "Border-collapse:collapse" bordercolor= #5555555 cellspacing=0 cellpadding=0 width=200 border=0>

<TR>
<TD align=middle bgcolor= #abc2d0 height=19 colspan= "2" ><B> train to Beijing </B> </TD>
</TR>
<tr>
<TD height= "> Car number:</td>"
<TD height= "id=" Cheh > </td>
</tr>
<tr>
<TD height= > Price:</td>
<TD height= "id=" "Price" > </td>
</tr>
</table>
</body>


Save the above code with the name autorefresh.jsp. In this file, the Createxmlhttprequest () function is used to create the asynchronous invocation object, the SendRequest () function is used to send the request to the client, and the ProcessResponse () function is used to handle the server-side response. Call the Displayhot () function to set the display style of the data during the process. The meaning of the settimeout ("SendRequest ()", 1000) function is to call the SendRequest () function every 1 seconds, which plays a leading role in Ajax page refreshes. The Displayhot () function is primarily used to parse the XML file returned from the server side and get the returned data, which is displayed on the current page.

Example 2

Below is the Include page containing the ajax.asp in the first page of the background:

The code is as follows Copy Code
<script type= "Text/javascript" >
<!--
Create a XMLHttpRequest Object
var xmlhttp;
try{
xmlhttp= new ActiveXObject (' msxml2.xmlhttp ');
}catch (e) {
try{
xmlhttp= new ActiveXObject (' microsoft.xmlhttp ');
}catch (e) {
try{
xmlhttp= new XMLHttpRequest ();
}catch (e) {}
}
}
function Getpart (URL) {
Xmlhttp.open ("Get", url,true);
Xmlhttp.onreadystatechange = function () {
if (xmlhttp.readystate = 4)
{
if (Xmlhttp.status = 200)
{
if (xmlhttp.responsetext!= "") {
document.getElementById ("Partdiv"). InnerHTML = Unescape (Xmlhttp.responsetext);
}
Else
{
document.getElementById ("Partdiv"). InnerHTML = "Data load Error";
}
}
}
}
Xmlhttp.setrequestheader ("If-modified-since", "0");
Xmlhttp.send (NULL);
}
SetInterval ("Getpart (' ordersound.asp ')", 50000);
-->
</script>
<div id= "Partdiv" style= "Display:none;" ></div>

Then we make an order query page, relatively simple, will do

New Order Query page:

The code is as follows Copy Code
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> Order Enquiry Page </title>
<body>
<!--#include file= "ajax.asp"-->
<%
SQLSTR = "SELECT count (*) as CCC from Yxb_order where Orderstatus=1"
Set rs = Conn.execute (SQLSTR)
If not rs.bof or not rs.eof then
Response.Write "<bgsound src=" prompts sound file. wav ' loop= ' 1 ' > '
End If
Rs.close
Set rs = Nothing
%>
</body>



Example 3, above all the original eco-Ajax, here is a jquery implementation method

The code is as follows Copy Code

<div class= "Le_top" id= "Ajaxlogin" >
</div>

jquery Ajax we can use load

The code is as follows Copy Code

$ (' #ajaxlogin '). Load (' ajaxlogin.php?cityid=1208 ');

The success of this loading will give the content to Ajaxlogin oh, compared to the above two kinds of jquery Ajax easy to be more concise oh.

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.