Using AJAX and Server (JSON) communication instances _javascript tips

Source: Internet
Author: User
Tags button type event listener http request

The word Ajax, which does not represent anything, is simply a term used to address a range of technologies that promote client-server communication. Server communication is the core of Ajax technology, the goal is to send information from the client to the server and accept the latter, in order to create a better user experience in the process.

All server communication before Ajax is done on the server, so it is a part of the page that you want to redraw, either using IFRAME (obsolete), or refreshing the entire page. Neither of these approaches is a good user experience.

Ajax provides two kinds of server communication means: Synchronous communication and asynchronous communication.

Asynchronous communication Ajax is much more common than synchronous communication, probably 98% of the usage frequency. Asynchronous means that such Ajax calls are not triggered at the same time as other tasks, which occur in the background, are quite independent and separate from the pages and Web applications.

With asynchronous invocations, you can avoid the blocking of a synchronous call, and it does not need to be squeezed together with other HTTP requests in the page.

XMLHttpRequest objects

The XMLHttpRequest object is the core of all Ajax calls. Our goal is to use AJAX technology to get the data in JSON asynchronously, and to show it in the proper form:

Create Ajax Communication Server object

function Gethttpobject () {

  "use strict";//note using strict mode

  var xhr;

  Use the mainstream XMLHttpRequest Communication Server object

  if (window). XMLHttpRequest) {

    xhr = new window. XMLHttpRequest ();

  In the case of an older version of IE, only active objects
  } else if (window) are supported. ActiveXObject) {

    xhr = new window. ActiveXObject ("Msxml2.xmlhttp");
  }

  Returns the communication server object to return
  xhr;

}

Cross-browser compatibility issues: Microsoft IE initially invented the XMLHTTP object, which led to IE5, IE6 only support ActiveXObject objects, so consider the compatibility issue.

Creating Ajax Calls

First, I created the Salad.json file in the local data directory and waited for the AJAX program to invoke it:

Ajax JSON Salad
var ingredient = {"
  fruit": [
    {
      "name": "Apple",
      "color": "Green"
    },
    { c8/> "name": "Tomato",
      "color": "Red"
    },
    {
      "name": "Peach",
      "color": "Pink"
    },
    { c16/> "name": "Pitaya",
      "color": "White"
    },
    {
      "name": "Lettuce",
      "color": "Green"
    }< c23/>]
};

The next thing to do is send the request and accept the data back to the server:

After receiving the returned server communication object "XHR", what we will do is to use the ReadyStateChange event to Ajax request state and server State for the communication object "XHR". The communication work after the ReadyState status request completes and the status status server is functioning normally.

Output the JSON data returned by the AJAX call

var request = Gethttpobject ();

Request.onreadystatechange = function () {

  "use strict";

    When the readyState all equals "4" state, status all equals "200" state service and client request normal, to return
  if (request.readystate ===4 | | request.status = = {
    
    //For convenience, print the data to the browser console (F12 view)
    Console.log (Request.responsetext);
  }
  
  Requests a. JSON data file using a Get method and does not send any information to the server
  request.open ("Get", "Data/ingredient.json", true);
  Request.send (null);


Ajax is also invoked through the Get and post methods, which exposes the data to the URL, so it works less; Post is relatively secure, but performance is not as good as got. Next, use the open () and send () methods to request data files and send data to the server.

Typically, it is not possible to have just one Ajax call in a real development project. To reuse, for convenience, we need to encapsulate this AJAX program into a reuse function where I pass in a outputelement parameter that prompts the user for a wait, and a callback parameter that passes in a callback function, The appropriate data is rendered to the page response location according to the keyword that the user typed in the search box to match in the JSON file:

Encapsulate it as a function

Ajaxcall (dataurl,outputelement,callback) {
  "use strict";  This is a truncated JS (Ajax) code

  var request = Gethttpobject ();
  I want to remind you that when an area of a Web page is sending an HTTP request to the server, an identity alert user is loading ...

  outputelement.innerhtml = "loding ..."; Can also be based on your needs to add a circular animation

  request.onreadystatechange = function () {

    if (request.readystate ===4 | | request.status ===200) {

      //convert Request.responsetext returned data into JSON format
      var contacts = Json.parse (request.responsetext);
      
      If the callback function is a function type, the callback function is used to process the returned JSON data
      if (callback = = "function") {
        callback (contacts);
      }
  };

  Request.open ("Get", "Data/ingredient.json", true);
  Request.send (null);
}

Then call Ajaxcall ():

Calling the program, we will display the JSON data using the AJAX request to an area of the HTML document!

    (function () {"Use strict"; The following will give the HTML code corresponding to the DOM statement var searchform = document.getElementById ("Search-form"), Searchfield = document.getelementbyi

  D ("Q"), Getallbutton = document.getElementById ("Get-all"), target = document.getElementById ("Output");
        var search = {Salad:function (event) {var output = document.getElementById ("Output"); The requested JSON data file name, output to the HTML area, retrieves the core function statement of the data file Ajaxcall (' Data/ingredient.json ', ' Output ', function (data) {//s Earchvalue for search entries, prepare to iterate over var searchvalue = Searchfield.value,//Find food items (see JSON data file) fruit = data

        . fruit,//statistics number of fruits count = fruit.length, I;

        Block default behavior Event.preventdefault ();

        Initialize target.innerhtml = ""; 
              if (Count > 0 | | | searchvalue!== "") {for (i = 0;i < count;i++) {var obj = Fruit[i], Place name with SearchvalThe UE value matches, if the value is not equal to-1, then determines that the two match initfount = obj.name.indexOf (Searchvalue); Writes the matching data specification in JSON to DOM if (Isitfount!=-1) {target.innerhtml = ' <p> ' +obj.name+ ' <a href
  = "mailto:" ' +obj.color+ ' > ' +obj.color+ ' </a></p> '}}}};
  
Event listener that calls the function after listening to the mouse click event and requests the JSON data file Searchfield.addeventlistener ("click", Search.salad,false);

 })();

Ajax-Corresponding HTML documents:

 
 

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.