Ajax asynchronous loading and parsing, ajax asynchronous loading

Source: Internet
Author: User

Ajax asynchronous loading and parsing, ajax asynchronous loading

AJAX (Asynchronous JavaScript and XML, Asynchronous JavaScript and XML ). It is not a new programming language, but a new method that uses existing standards. It is an art of exchanging data with the server and updating some webpages without reloading the entire page.
Let's join in the AJax world.

Basic syntax

Before learning about Ajax, we need to clarify our own needs, that is, to achieve Asynchronous interaction with the server without refreshing new pages, and to update page information. Ajax is actually very easy to use. We only need to follow certain steps.
• Create an Ajax object (native needs to determine the type of the current browser)
• Set the callback function (the function triggered after interaction with the server)
• Open the request and send it. (Code writing is slightly different depending on the Request Method)
• The client obtains feedback and updates the page.

Get Ajax objects

Different browsers have different support for Ajax, so we need to treat them differently.

Set callback function

The purpose of setting the callback function is to add the obtained data to the page after Ajax interacts with the server.

We usually specify the onreadystatechange function as our callback handler.

The following status information related to Ajax interaction with the server is provided for our reference during encoding.

. Readystate

There are several common values about the loading status:
• 0: the request is not initialized.
• 1: The server connection has been established
• 2: The request has been received
• 3: The request is being processed
• 4: The request is complete and the response is ready

. Status

The status information of the loading result is as follows:
• 200: "OK"

• 404: "This page is not found"

 Enable Interaction

When talking about interaction, the two sides come to mind. That is, the interaction between our ajax client and the server. Therefore, we need to specify the location of the request data on the server.

Open (method, url, async)

The use of the url varies with the method, which must be clear. As for the asynchronous parameter, generally, false can be used for requests with a small amount of data, but it is recommended to use true for asynchronous loading to avoid excessive server pressure.

 • GET Method

It's easy to use this method, just specify the url location on the server. Here, the red part is very important. We must specify the url as the location of the request on the server. The absolute path is generally used.

// For Servlet, you can specify the location on the annotation to xmlhttp. open ("GET", "/Test/servlet/AjaxServlet? Userinput = "+ str. value, true); xmlhttp. send ();

• POST Method 

When using POST, we need to handle one more item. For example:

Xmlhttp. open ("POST", "ajax_test.asp", true); xmlhttp. setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // specify the parameter information to be transmitted in the send method to xmlhttp. send ("fname = Bill & lname = Gates ");

Client Update page

For Ajax, as the name implies. Data is transmitted in xml format. But for now, this is no longer the only form. So how can we update the obtained data to the webpage? There are two methods.
• If the response from the server is not XML, use the responseText attribute.
Document. getElementById ("myDiv"). innerHTML = xmlhttp. responseText;

• If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute:

xmlDoc=xmlhttp.responseXML;txt="";x=xmlDoc.getElementsByTagName("ARTIST");for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; }document.getElementById("myDiv").innerHTML=txt;

Instance experience

After understanding these basic syntaxes, we can simply use them in actual development. To better complete this experiment, I first made a simple JavaWeb to process our Ajax requests.

Servlet

AjaxServlet. java

Package one; import java. io. IOException; import java. io. printWriter; import javax. servlet. servletException; import javax. servlet. annotation. webServlet; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse;/*** Servlet implementation class AjaxServlet */@ WebServlet ("/AjaxServlet") public class AjaxServlet extends HttpServlet {pr Ivate static final long serialVersionUID = 1L;/*** @ see HttpServlet # HttpServlet () */public AjaxServlet () {super (); // TODO Auto-generated constructor stub}/*** @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse * response) */protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method Stub // response. getWriter (). append ("Served :"). append (request. getContextPath (); String userinput = request. getParameter ("userinput"); System. out. println ("client connection! "); System. out. println ("Request Information:" + userinput); PrintWriter out = response. getWriter (); if (userinput. equals ("") | userinput. length () <6) {response. setContentType ("text/html; charset = UTF-8"); response. setCharacterEncoding ("UTF-8"); response. setHeader ("Content-Type", "text/html; charset = UTF-8"); out. write ("

Web. xml

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Test</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>AjaxServlet</servlet-name> <servlet-class>one.AjaxServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServlet</servlet-name> <url-pattern>/servlet/AjaxServlet</url-pattern> </servlet-mapping></web-app>

Ajax.html

<! DOCTYPE html> 

• Length greater than or equal to 6:

Use JSP

ReceiveParams. jsp

<% @ Page contentType = "text/html; charset = UTF-8" language = "java" %> <% // receive parameter String userinput = request. getParameter ("userinput"); // The console outputs the form data to see the System. out. println ("userinput =" + userinput); // check the validity of the code if (userinput = null | userinput. trim (). length () = 0) {out. println ("code can't be null or empty");} else if (userinput! = Null & userinput. equals ("admin") {out. println ("code can't be admin");} else {out. println ("OK") ;}%>

Ajax.html

<! DOCTYPE html>  $.post("./newProject",{newProjectName:project_name},   function(data,status){  //alert("data:" + data + "status:" + status);  if(status == "success"){   var nodes = data.getElementsByTagName("project");   //alert(nodes[0].getAttribute("name"));   for(var i = 0;i < nodes.length;i ++){    $("#project_items").append("<option value=\"" + (i+1) + "\">" + nodes[i].getAttribute("name") + "</option>");    }  } })

•. Ajax

$ (Function () {// execute $ ("# testAjax") when the button is clicked "). click (function () {// Ajax call processing $. ajax ({type: "POST", url: "test. php ", data:" name = garfield & age = 18 ", success: function (data) {$ ("# myDiv" ).html ('

•. Get Method

 $(document).ready(function(){ $("#bt").click(function(){ $.get("mytest/demo/antzone.txt",function(data,status){  alert("Data:"+data+"\nStatus:"+status); }) })})

Summary

In today's demonstration, it is necessary for users on the server to input data for verification during actual development, or to instantly update pages to reduce network traffic. It is also widely used and can effectively improve the user experience.

In this case, we should give a reference and add asynchronous loading to your application.

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.