Ajax Experience 3--writing Ajax with Labor Code and case analysis

Source: Internet
Author: User
Tags flush
1. Initialize the XMLHttpRequest object template function Createxmlhttprequest () {var xmlHttp;
    try{//firefox, Opera 8.0+, Safari xmlhttp=new XMLHttpRequest ();
            }catch (e) {try{//internet Explorer xmlhttp=new activexobject ("msxml2.xmlhttp");
                  }catch (e) {try{xmlhttp=new ActiveXObject ("Microsoft.XMLHTTP");
 }catch (e) {}}} return xmlHttp;

2. Manually write Ajax generic tool code//Get DOM Object function $ (ID) {return document.getElementById (ID) by ID;
	Ajax technology must create a XMLHttpRequest object to get the operation function of the XMLHttpRequest object Createxhr () {var xhr; var aversion = ["msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", "Microsoft.XMLHtt
	P "];
	try {//high version ie, Firefox, Opera and other browsers directly new Ajax object XHR = new XMLHttpRequest ();  A catch (E) {//lower version of IE,IE6 needs to create Ajax objects for (var i = 0; i < aversion.length; i++) {try {xhr = new ActiveXObject (Aversion[i]);
			return XHR;
			catch (e) {continue;
}} return XHR;

	3.ajax Processing Paging technology Case window.onload = function () {//Get button object var querybtndom = $ ("querybtn");
		Set Click event Action Querybtndom.onclick = function () {var content = "pagination.nowpage=" + 1;
		var url = "./csdn/useraction_query.action?time=" + new Date (). GetTime ();

		Invoke Ajax-processed requests to send operations Sendpost (content, URL, managersuccess, managerfail);
			Handle Successful method function Managersuccess (XHR) {//Create XML DOM object var xmldom = Xhr.responsexml;
			Create XML with object var root = xmldom.documentelement;
			Gets the child node of the object var users = root.getelementsbytagname ("user");

			Display data manipulation showusers (users); Paging operation//home $ ("FirstPage"). onclick = function () {//Reset the value for the requested data and resend the request content = "Pagination.nowpage
				= "+ 1;
			Sendpost (content, URL, managersuccess, managerfail);
			}; Previous $ ("BackPage"). onclick = function () {//Reset the value of the requested data and resend the request content = "Pagination.nowpage=" + Eval (root.GetAttribute ("nowpage") + "-" + 1);

			Sendpost (content, URL, managersuccess, managerfail);
			}; Next $ ("NextPage"). onclick = function () {//Reset the value of the requested data and resend the request content = "Pagination.nowpage=" +
				Eval (Root.getattribute ("nowpage") + "+" + 1);

			Sendpost (content, URL, managersuccess, managerfail);
			}; Last $ ("LastPage"). onclick = function () {//Reset the value of the requested data and resend the request content = "Pagination.nowpage=" + R
				Oot.getattribute ("Countpage");
			Sendpost (content, URL, managersuccess, managerfail);
		};
		function Managerfail (XHR) {alert ("process failed");
}

	};

}; Encapsulates a method function that creates element elements CE (tag) {return document.createelement (tag);}//Encapsulate a method to create a text node function CT (t) {return
document.createTextNode (t);
	///Send the requested method function Sendpost (content, URL, success, fail) {var xhr = createxhr (); Trigger Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {if (Xhr.status = = | | xhr.status = = 304)
{success (XHR);			else {fail (XHR);
	}
		}
	};
	Open the request Xhr.open ("POST", url, True);
	Set type Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
	Send request xhr.send (content);
// };
	}///Display data method function Showusers (users) {//Get Tbody dom object var tbodydom = $ ("showusers"); Empty data if (Tbodydom.haschildnodes ()) {for (var JJ = 0; JJ < tbodyDom.childNodes.length;)
		{Tbodydom.removechild (TBODYDOM.CHILDNODES[JJ]);
		}///Traversal Add data for (var i = 0; i < users.length i++) {var user = Users[i];

			if (User.nodetype = = 1) {///Create TR element node var tr = CE ("tr");
			Create a TD element node//Create a checkbox node var td1 = CE ("TD");
			var input = CE ("input");
			Set the property Input.setattribute ("type", "checkbox") for TD1;

			Input.setattribute ("Value", User.getattribute ("id"));
			var td2 = CE ("TD");
			var td3 = CE ("TD");
			var td4 = CE ("TD");
			var TD5 = CE ("TD");
			var td6 = CE ("TD");

			var td7 = CE ("TD"); Append the text node to the TD; Note that you cannot use the method chain to append, otherwise the interface will make you difficult to td1.appendchild (inPut);
			Td2.appendchild (CT (User.getattribute ("id"));
			Td3. AppendChild (CT (User.getelementsbytagname ("name") [0].firstchild.nodevalue)];
			Td4. AppendChild (CT (User.getelementsbytagname ("Sex") [0].firstchild.nodevalue)];
			Td5. AppendChild (CT user.getelementsbytagname ("email") [0].firstchild.nodevalue)];

			Td6. AppendChild (CT (user.getelementsbytagname ("Birthday") [0].firstchild.nodevalue)];
			The TD is appended to the TR Upper Tr.appendchild (TD1);
			Tr.appendchild (TD2);
			Tr.appendchild (TD3);
			Tr.appendchild (TD4);
			Tr.appendchild (TD5);
			Tr.appendchild (TD6);
			Tr.appendchild (TD7);
		Adds a TR node to the Tbody tbodydom.appendchild (TR); The user name is registered with AJAX validation Processing window.onload=function () {///the DOM object based on the ID for data that needs to be processed with Ajax technology, Util.js and Reg.js are located under the same package, and solid can reference Var unamed
	Om = $ ("UserName");
		Event that loses focus for unamedom registration Unamedom.onblur=function () {//to encapsulate the acquired username name into the request data var content = "Uname=" +unamedom.value; Sets the request path and generates a unique URL var url = "./csdn/useraction_checkname.action?time=" +new date () in the form of a timestamp.. GetTime ();
		
		Create Ajax object var xhr = CREATEXHR ();
		Where the state is 0, the default value of the state is 0, indicating that the onReadyStateChange event//alert (xhr.readystate) is triggered from 0 to 1 o'clock; Sets a trigger event for the XHR object, and the event server handles Xhr.onreadystatechange=function () {//alert (xhr.readystate) itself; The state executes from 1-4 if (xhr.readystat e==4) {if (xhr.status==200| |
				xhr.status==304) {$ (' name '). Innerhtml=xhr.responsetext;
		}
			}
		};
		Open Request Xhr.open ("POST", url,true); If a POST request needs to do the following, tell the browser to send data that matches the URL encoding; A word in parentheses cannot be wrong, and one cannot pass the data to the servlet xhr.setrequestheader ("Content-type", "
		Application/x-www-form-urlencoded ");
	Send data xhr.send (content);
};

};

Action processing code package www.csdn.project.action;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Javax.servlet.http.HttpServletResponse;
Import Org.apache.struts2.ServletActionContext;
Import Www.csdn.project.domain.User;
Import Www.csdn.project.service.UserService;
Import Www.csdn.project.service.UserServiceImpl;

Import www.csdn.project.utils.Pagination; Import Com.opensymphony.xwork2.ActionSuppoRt
	
	public class Useraction extends Actionsupport {private String uName;
	
	The current page property of pagination, where you must indicate the type the generic is pointing to, or else it will be wrong. Private pagination<user> pagination;

	Declares a transaction object private UserService service = new Userserviceimpl (); Gets the response object through the Servletactioncontext class, moves the actions in action to the servlet's operations private httpservletresponse response =
	
	Servletactioncontext.getresponse ();
	
	
	

	Declares an output object private printwriter out;
	Public pagination<user> getpagination () {return pagination;
	public void Setpagination (pagination<user> pagination) {this.pagination = pagination;
	Public String Getuname () {return uName;
	You must pay attention to naming conventions, set injection methods and get-valued method initials must be capitalized, otherwise it will not work remember that public void Setuname (String uName) {this.uname = UName;
	//Login Operation public String login () {return SUCCESS;
		
		//Check name Public String checkname () {Response.setcontenttype ("text/html;charset=utf-8");
		Instantiate the Out object try {out = Response.getwriter (); catch (IOException e) {e.printstacktrAce ();

		User entity = Service.getobjectbyname (uName);
		if (entity!= null) {out.print ("User name already exists");
		else {out.print ("User name can be used");
		} out.flush ();
		Out.close ();
	Return "Reg";
		//Find All Public String query () {Response.setcontenttype ("text/xml;charset=utf-8");
		System.out.println (Pagination.getnowpage () + "====================");
		pagination = new Pagination<user> (User.class,pagination.getnowpage ());
		Instantiate the Out object try {out = Response.getwriter ();
		catch (IOException e) {e.printstacktrace ();
		//Spell out the XML file to store the data extracted from the database Out.println ("<?xml version= ' 1.0 ' encoding= ' UTF-8 ')"; Out.println ("<users nowpage=" "+pagination.getnowpage () +" ' countpage= ' "+pagination.getcountpage () +" "
		Countrecond= ' "+pagination.getcountrecond () +" ' > ");
			Traversal for (User entity:pagination.getEntities ()) {Out.print ("<user id= '" +entity.getid () + "' >");
			Out.print ("<name>");
			Out.print (Entity.getname ());
		Out.print ("</name>");	Out.print ("<sex>");
			Out.print (Entity.getsex ());
			Out.print ("</sex>");
			Out.print ("<birthday>");
			Out.print (Entity.getbirthday ());
			Out.print ("</birthday>");
			Out.print ("<email>");
			Out.print (Entity.getemail ());
			Out.print ("</email>");
		Out.print ("</user>");
		
		} out.println ("</users>");
		Refreshes the out object so that the data is not stored in the cache and directly displays Out.flush ();
		Out.close ();
	return "XML"; The paging Display Interface <%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%@ taglib uri= "/struts-tags" p Refix= "S"%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >  

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.