Ajax asynchronous load parsing _ajax related

Source: Internet
Author: User
Tags stub

AJAX (Asynchronous JavaScript and XML, asynchronous JavaScript and XML). It is not a new programming language, but a new way of using existing standards, the art of exchanging data with servers without reloading the entire page and updating portions of the Web page.
So let's go into the Ajax world together.

Basic syntax

Before learning Ajax, we need to be clear about their needs, that is, without refreshing the page under the premise of the implementation of asynchronous and server interaction, update page information. The use of Ajax is also very simple, we only need to follow a certain step.
• Create Ajax objects (native needs to determine the type of current browser)
• Set up callback functions (functions that are triggered after interacting with the server)
• Open the request and send it. (Code writing is slightly different depending on how you request it.)
• Client get feedback data, update page

Get Ajax objects

The support of different browsers for Ajax is inconsistent, so we need to treat them differently.

Set callback function

The purpose of setting up a callback function is to add the acquired data to the page after Ajax has finished interacting with the server.

Normally we will specify the onReadyStateChange function as our callback handler function.

Related to Ajax and server interaction with the following state information for us in the coding process to find the reference.

. readystate

There are several common values for loading states:
• 0: Request not initialized
• 1: Server connection has been established
• 2: Request received
• 3: Request processing
• 4: The request is complete and the response is ready

. Status

The status information for the load result is:
200: "OK"

• 404: "This page was not found"

Open Interactive

When it comes to interaction, it's on both sides. That is, the interaction between our AJAX client and the server. So we need to explicitly request the location of the data on the server

Open (Method,url,async)

The use of URLs differs depending on method, which we must be clear about. As for asynchronous this parameter, generally a small amount of data requests can be false, but it is recommended to use true for asynchronous loading to avoid server stress.

Get Way

This is simply the way to specify the location of the URL on the server. The red part of the understanding here is quite important. We must specify that the URL is the location of the request on the server, typically using an absolute path.

The servlet specifies the position on its annotation to
xmlhttp.open ("Get", "/test/servlet/ajaxservlet?userinput=" +str.value,true);
  Xmlhttp.send ();

Post Way

When using the Post method, we need an extra deal. The following example:

Xmlhttp.open ("POST", "ajax_test.asp", true);
Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
Specify the parameter information to be transferred in the Send method
xmlhttp.send ("fname=bill&lname=gates");

Client Update page

For Ajax, as the name suggests. is to transmit data in XML form. But for now, this is no longer the only form. So how do we update the data we get to the Web? There are two different ways.
• Use the ResponseText property if the response from the server is not XML.
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 property:

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

With this basic syntax, we can simply apply it in real-world development. To better complete this experiment, I first made a simple javaweb to deal with our Ajax request.

Using the Servlet method

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 HTTPSERVL

 Et {private static final long serialversionuid = 1L;
  /** * @see httpservlet#httpservlet () * * * Public ajaxservlet () {super (); TODO auto-generated Constructor stub}/** * @see httpservlet#doget (httpservletrequest request, httpservletrespons E * Response) */protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexc Eption, IOException {//TODO auto-generated Method Stub//response.getwriter (). Append ("served at:"). Append (request.g
  Etcontextpath ());
  String userinput = Request.getparameter ("Userinput"); System.out. println ("Client connection!")
  ");
  SYSTEM.OUT.PRINTLN ("Request information is:" + 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&Gt

 </servlet-mapping> </web-app>

Ajax.html

<! DOCTYPE html> 
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%> 
<% 
  //Receive parameters 
  String userinput = Request.getparameter ("Userinput"); 
  Console output form data look at 
  System.out.println ("userinput =" + userinput); 
  Check the legality 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 { C13/>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 Way

 $ (function () {
  //button click to execute
  $ (' #testAjax '). Click (function () {

    //ajax call handles
   $.ajax ({
    type: POST),
    URL: "test.php",
    data: "Name=garfield&age=18",
    success:function (data) {
      $ ("#myDiv"). HTML ('  
 

.get Way

 $ (document). Ready (function () {
 $ ("#bt"). Click (function () {
 $.get ("Mytest/demo/antzone.txt", function ( Data,status) {
  alert ("Data:" +data+ "\nstatus:" +status);
 })
 })

Summarize

Today's demo for the actual development of the process, server-side user input data validation, or real-time update of the page and reduce network traffic is very necessary. The utility is also very extensive, but also can effectively enhance the user experience.

This case, as a trigger, to your application also add asynchronous load it.

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.