Jquery Ajax Basics Tutorial _jquery

Source: Internet
Author: User
Tags error handling eval getscript i18n

jquery Ajax brings a Web page revolution that doesn't need to be refreshed. Here is a detailed description of the AJAX operations involved in jquery. (No special instructions, all need to have server configuration, here I use Tomcat 7)

1. Load file data based on request

The requests here are usually some of the web's operations, such as clicks.

The types of data that they load are grouped into the following four categories: A. load HTML file; b. load the JSON file; c. load the JavaScript file; d. load the XML file.

The corresponding four kinds of loading methods are: Load, Getjson, Getscript, get.

A. Loading HTML files

Load the prepared HTML file into the Web page. For example:

The Load method loads the HTML file 
$ (' #letter-a '). Click (function () { 
    $ (' #dictionary '). Load (' a.html '); 
    return false; 
});

Here a.html is also placed on the server side of a prepared page file, call load directly, you can match the target to load the HTML content.

B. Loading a JSON file

Load the prepared JSON file into the Web page. For example:

//load JSON file $ (' #letter-B a '). Click (function () {$.getjson (' B.json ', function (data) { 
    var html = '; 
      $.each (Data,function (Entryindex, entry) {html = "<div class= ' entry ' >"; 
      HTML + + "

Getjson method The first parameter is the file path that is loaded, and the second parameter is a callback function after the load completes. With this callback function, the loaded data can be manipulated. The repeating section is processed using each loop. Finally, the cobbled HTML string is added to the target Id=dictionary element using the HTML method.

C. Loading JavaScript files

Loading JavaScript files is similar to loading HTML files. It should be noted here that JavaScript loaded in using the Getscript method will run directly according to the current JavaScript environment. For example:

Execute script 
$ (' #letter-c a '). Click (function () { 
    $.getscript (' c.js '); 
    return false; 

d. loading XML files

In jquery, you can use the Get method to load an XML file. For example:

Load XML document $ (' #letter-D a '). Click (function () {$.get (' d.xml ', function (data) {$ (' #dictionary '). empty (); 
        $ (data). Find (' entry '). each (function () {var $entry = $ (this); 
        var html = ' <div class= ' entry ' > '; 
        html = ' 

One of the features of an XML file is that you can manipulate the elements of XML as you would with jquery operations HTML. such as using the Attr method, the text method, and so on.

2. Getting data to the server based on the Get method

The previous example is to obtain data files statically from the server. And the value of Ajax not only this, through the Get method from the server dynamic access to data, for the Web page without the realization of the refresh provides a great help.

The following uses the Get method to fetch the required data from the server. Here, I combine the Java-EE Struts2 framework and Tomcat built server side. A variety of server-specific, can be php+apache or anything else can be.

The operation is as follows, the user clicks Eavesdrop sends the GET method to the server, obtains the eavesdrop the data, and returns the JSON value, then assembles in the jquery.

The code is as follows:

The Get method loads the server contents $ (' #letter-e a '). Click (function () {var requestdata = {term:$ (this). Text (). toUpperCase ()}; $.get (' eget.action ', requestdata, function (data) {//returned packet structure is configured according to STRUTS2 as follows://{"resultmsg": "{another JSON inside 
      Structure} ', ' Success ': ' true '/////First unpacking the returned packets var responseobj = eval ("+data+")); 
        if (responseobj.success = = ' true ') {$ (' #dictionary '). empty (); 
        Return success, Next unpack resultmsg var dataobj = eval ("+responseobj.resultmsg+")); 
        var html = ""; 
        HTML + + "<div class= ' entry ' >"; 
        HTML + + "

This is explained by the STRUTS2 configuration, which, when returned, has a layer of packets outside the required data to indicate the resultmsg of the result content and whether Ajax accesses the Success field successfully. So 2 eval solutions were used.

Here I am passing the background Java program is not configured HTML, but only the JSON type of data, I think in the Java level to write HTML and delivery is not as convenient as direct data transfer, later modify the style or page structure is not as easy as directly modify JavaScript.

Getting the server data through the Get method is equivalent to submitting the following request to the server: eget.action?term=xxx

The following release Java background file code:

1.eget.java

Package LHB; 
Import Com.opensymphony.xwork2.ActionSupport; 
  public class Eget extends Actionsupport {private String term; 
  Private Terms sampleterm; 
  Private String success; 
  Private String resultmsg; 
  /** * */private static final long serialversionuid = 1L; 
    Public String Execute () throws Exception {InitData (); 
      if (Term.equals (Sampleterm.getterm ())) {success = "true"; resultmsg = "{\" term\ ": \" "+sampleterm.getterm () +" \ "," + "\" part\ ": \" "+sampleterm.getpart () +" \ "," + " \ "definition\": \ "" +sampleterm.getdefinition () + "\" "+" \ "quote\": ["+" \ "is public worship, then, a 
          Sin,\ "," + "\" "That's for devotions paid to Bacchus\", "+" \ "The lictors dare to run US in,\", "+ 
    "\" and resolutely thump and whack us?\ "+"], "+" \ "author\": \ "" +sampleterm.getauthor () + "\"}; 
      } else{Success = "false"; 
    Resultmsg = "Fail"; 
 }   return SUCCESS; 
    }//Initialize data private void InitData () {String Parteavesdrop = "v.i."; 
    String Definitioneavesdrop = "secretly to overhear a catalogue of the crimes and vices of the another or yourself."; String quoteeavesdrop[] = {"A lady with one of the her ears applied", "to a open keyhole heard, inside,", " Two female gossips in Converse free-"," the subject engaging-them was she. "," "I think,\" said one, \ " And my husband thinks "," that she's a prying, inquisitive minx!\ "", "as soon as no more of it she could 
        Hear "," The Lady, indignant, removed her ear. "," \ I won't be stay,\ "she said, with a pout,", 
    "\" To hear my character lied about!\ ""}; 
    String Authoreavesdrop = "Gopete sherany"; 
    Terms eavesdrop = new Terms (); 
    Eavesdrop.setterm ("eavesdrop"); 
    Eavesdrop.setpart (Parteavesdrop); 
    Eavesdrop.setdefinition (Definitioneavesdrop); Eavesdrop.setquote (quoteeavesDROP); 
    Eavesdrop.setauthor (Authoreavesdrop); 
  Sampleterm = eavesdrop; 
  Public String Getterm () {return term; 
  } public void Setterm (String term) {this.term = term; 
  Public String getsuccess () {return success; 
  } public void Setsuccess (String success) {this.success = success; 
  Public String getresultmsg () {return resultmsg; 
  } public void Setresultmsg (String resultmsg) {this.resultmsg = resultmsg;  } 
}

This action in the data I directly configured, here is just a demonstration to use. The real data is typically stored in the database in the project. Since this is primarily a small example of jquery, it's no bother.

2.terms.java

Package LHB; 
public class Terms 
{ 
  private String term; 
  Private String part; 
  private String definition; 
  Private String quote[]; 
  Private String author; 
  Public String getterm () 
  {return 
    term; 
  } 
  public void Setterm (String term) 
  { 
    this.term = term; 
  } 
  Public String Getpart () 
  {return part 
    ; 
  } 
  public void Setpart (String part) 
  { 
    This.part = part; 
  } 
  Public String getdefinition () 
  {return 
    definition; 
  } 
  public void setdefinition (String definition) 
  { 
    this.definition = definition; 
  } 
  Public string[] GetQuote () 
  {return 
    quote; 
  } 
  public void Setquote (string[] quote) 
  { 
    this.quote = quote; 
  } 
  Public String Getauthor () 
  {return 
    author; 
  } 
  public void Setauthor (String author) 
  { 
    This.author = author; 
  } 

This class is purely a Pojo class. There's no particular way.

3.struts.xml

This is struts2 json-way delivery configuration

<?xml version= "1.0" encoding= "UTF-8"?> <! 
DOCTYPE struts public 
  "-//apache Software foundation//dtd struts Configuration 2.3//en" 
  "http:// Struts.apache.org/dtds/struts-2.3.dtd "> 
<struts> 
  <!--Specify global internationalization resource files--> 
  <constant Name= "Struts.custom.i18n.resources" value= "i18n"/> 
  <!--Specifies the character set used for internationalized encoding--> <constant name= 
  " Struts.i18n.encoding "value=" GBK "/> 
  <!--json action--> <package name=" Jsoninfo "extends=" 
  Json-default "> 
    <action name=" eget "class=" LHB. Eget "> 
      <result type=" json "> 
        <param name=" ContentType ">text/html</param> 
        < param name= "includeproperties" >success, resultmsg</param> 
      </result> 
    </action> 
  </package> 

Here you can see the outer layer of json,success and resultmsg that are configured in the Includeproperties. This is very useful in practice. If the desired value is not obtained in the server, the Ajax access succeeds, but the results are not successful because the desired value is not obtained. The success is added here to facilitate the front desk jquery operation.

Obtaining server data based on other methods is basically consistent with get, such as Post method and load method. Here is no longer to repeat.

3. Dynamic submission of forms

With the Ajax support of jquery, it makes it easy for us to submit the form dynamically without refreshing the page.

As in the following example:

$ (' #letter-f form '). Submit (function () {//Call Preventdefault method to prevent event bubbling, which is to prevent the submission of form forms if the Web page has a script error event.preventd 
    Efault (); 
    var formvalues = $ (' input[id= ' term '] '). Val (); 
    var requeststr = {' term ': Formvalues.touppercase ()}; 
      $.get (' eget.action ', requeststr, function (data) {var responseobj = $.parsejson (data); 
        if (responseobj.success = = ' true ') {var html = '; 
        var dataobj = $.parsejson (responseobj.resultmsg); 
        HTML + + "<div class= ' entry ' >"; 
        HTML + + "

The data cited in this example is the one used by the previous eget.action. The process of operation of the program is basically:

This preventdefault () is called first, and this method is also explained in the comments to prevent the inconvenience and trouble caused by event bubbling.

Next, you get the element of input by $ () and use the Val method to get its value, and the next method is basically the same as the previous example.

Here you can also use the Serialize method to serialize the input element to the format "Term=xxx" as follows. But because of the data in the server-side Java program hard-coded, all, not too convenient to use, it is useless.

4. Observer functions on Ajax

jquery contains 2 GLOBAL AJAX observer functions: Ajaxstart and Ajaxstop.

Called at the start and end of an AJAX operation, respectively. For example:

Ajax observer functions Ajaxstart and Ajaxstop 
  $ (' <div id= ' loading ' >Loading...</div> '). InsertBefore (' # Dictionary ') 
    . Ajaxstart (function () { 
      $ (this). Show (); 
    }). Ajaxstop (function () { 
      $ (this). Hide (); 
    

Regardless of which a tag triggers AJAX operations, including static loading files and dynamic server access, Ajaxstart and ajaxstop are triggered.
About error handling, commonly used three functions: success, complete, error.

The following is an example of error:

. Error (function (JQXHR) { 
  $ (' #dictionary '). HTML (' An error occurred: ' + jqxhr.status). Append (Jqxhr.responsetext); 

You can place the error method after the Get method in consonant: "$.get (). Error ()".
Just looked, this can be Tomcat's error, loaded onto the page. This is useful in some cases. As shown in figure:

But do not know why this will be my original style also covered some, if any netizens know, please correct the problem. Thank you, sir.

5.Ajax and Events

Ajax dynamic access to the server-generated elements, if you want to bind events, one method is to each fetch to rebind the handler, which is relatively simple, but not suitable for the DOM structure often changes in the scene. If the DOM structure changes frequently, you need to implement the event delegate using the Live method.

Live usage is the same as bind.

About jquery Ajax Basic tutorial Today small series to introduce to you here, follow-up will continue to introduce to you, I hope that we continue to pay attention to cloud habitat community sites, have your attention we will do better, thank you!

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.