Brief introduction to write Ajax_ajax related without library (framework)

Source: Internet
Author: User
Tags html form script tag unique id

It is common to use AJAX to request data, load a library (frame), and perhaps just maybe the ajax part.

Write an Ajax, one can experience the process of dealing with problems, improve the technical capacity, and sometimes the work does not need such a large library (frame), with their own written, he le it.

Let's take a look at how popular jquery invokes Ajax.

$.ajax ({
  URL:    ' test.php ',   //Send request URL string
  type:    ' get ',     //Send Way 
  dataType:  ' json ',     //Expected server-returned data type XML, HTML, text, JSON, JSONP, script data
  :    ' k=v&k=v ',///sent to the   date 
  async:   true,      ///Asynchronous Request 
  cache:   false,//     cache 
  timeout:  5000,//      timeout milliseconds
  Beforesend:function () {},  //Before request
  Error:   function () {},  /////////////
  Success:  function () {},  ///When the request succeeds
  complete:  function () {}  //request completed (either successful or unsuccessful)
});

Such a call is not very comfortable, convenient, if feel comfortable that oneself write also refer to this design way, not too complex, to meet the needs of the good.

Learn the basics of Ajax first

  XMLHttpRequest objects

The XMLHttpRequest object is the core of Ajax, with XMLHttpRequest objects to send asynchronous requests to the server to obtain data from the server, all modern browsers (ie7+, Firefox, Chrome, Safari, Opera) support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject).

  To create a compatible XMLHttpRequest object

var xhr = window. XMLHttpRequest? New XMLHttpRequest (): New ActiveXObject (' microsoft.xmlhttp ');

send a request to the server

Xhr.open (Method,url,async);
Method: The requested type; get or POST
URL: Requested URL
Async:true (asynchronous) or false (synchronous)
Xhr.send (string);
Send a request to the server
String: for POST requests only
Get is simpler and faster than POST requests and can be used in most cases
Use POST requests in the following situations:
Unable to use cache file (update file or database on server)
Send large amounts of data to the server (POST no data limit)
Post is more stable and reliable than get when sending user input with unknown characters

  Server response

Use the ResponseText or Responsexml property of the XMLHttpRequest object to obtain a response from the server.

If the response from the server is XML and needs to be parsed as an XML object, use the Responsexml property.

If the response from the server is not XML, use the ResponseText property, and the ResponseText property returns the response in the form of a string.

 onReadyStateChange Events

When the request is sent to the server, we need to perform some response based tasks. Whenever the readyState changes, the onReadyStateChange event is triggered. The ReadyState property contains the state information of the XMLHttpRequest.

  The three important properties of the XMLHttpRequest object:

    onreadystatechange //stored functions (or function names) that are called whenever the ReadyState property is changed

    readyState //presence of XMLHttpRequest, varying from 0 to 4

0: Request not initialized
1: The server connection has been established
2: Request received
3: In Request processing
4: The request is complete and the response is ready

    status //200: "OK", 404: Page Not Found

In the onReadyStateChange event, we specify that the response is ready when the server responds to a task that is ready to be processed, when the readystate equals 4 and the status is 200.

Xhr.onreadystatechange = function () {
  if (xhr.readystate = 4 && xhr.status =) {
    //ready to handle returned xhr.re Sponsetext or Xhr.responsexml 
  }
};

A simple Ajax request is as follows:

var xhr = window. XMLHttpRequest? New XMLHttpRequest (): New ActiveXObject (' microsoft.xmlhttp ');
Xhr.onreadystatechange = function () {
  if (xhr.readystate = 4 && xhr.status =) {
    //ready to handle returned xhr.re Sponsetext or Xhr.responsexml 
  }
};
Xhr.open (Method,url,async);
Xhr.send (string);

Added: 1. When you send a GET request, you may receive a cached result, and to avoid this situation, you can add a unique ID, timestamp, to the URL. 2. If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. Then send the data in the Send () method.

url = = (Url.indexof ('? ') < 0? '? ': ' & ') + ' _= ' + (+new Date ());
Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded ');

  Start to write your own Ajax

First write a basic, defined various parameters options, for reference

var $ = (function () {//auxiliary function serialization parameter function param (data) {//.. function Ajax (opts) {var _opts = {url: '/',///Send Request URL address type: ' Get ',////Send Request Way G       ET (default), POST dataType: ',//expected server returned data type XML, HTML, text, JSON, JSONP, script data:null, Sent data ' Key=value&key=value ', {key:value,key:value} async:true,//Asynchronous request Ture (default asynchronous), False Cach
      E:true,//cache Ture (default cache), False timeout:5,//timeout default 5 Seconds Load:function () {},//Request loading Error:function () {},///////////////////////////////////////////Success:function Regardless of success or failure)}, aborted = False, key, xhr = window. XMLHttpRequest?
    New XMLHttpRequest (): New ActiveXObject (' microsoft.xmlhttp ');        
     
    For (key in opts) _opts[key] = Opts[key];
    /* if (_opts.datatype.tolowercase () = = = ' script ') {///... } if (_opts.datatype.tolowercase () = = ' Jsonp'){
      //.. }/if (_opts.type.touppercase () = = ' Get ') {if (param (_opts.data)!== ') {_opts.url = (_opts.url.i Ndexof ('? ') < 0?
      '? ': ' & ') + param (_opts.data); }!_opts.cache && (_opts.url = = (_opts.url.indexof ('? ') < 0?
    '? ': ' & ') + ' _= ' + (+new Date ());
        The function checktimeout () {if (xhr.readystate!== 4) {aborted = true;
      Xhr.abort ();
     
    } settimeout (Checktimeout, _opts.timeout*1000);
      Xhr.onreadystatechange = function () {if (xhr.readystate!== 4) _opts.load && _opts.load (XHR);
        if (xhr.readystate = = 4) {var s = xhr.status, xhrdata; if (!aborted && ((s >= && s <) | | s = = 304)) {switch (_opts.datatype.tolowercase (
            ) {case ' xml ': Xhrdata = xhr.responsexml;
            Break Case ' json ': xhrdata = window. JSON && windows. Json.parse? Json.parse (Xhr.responsetext): eval (' (' + xhr.responsetext + ') ');
            Break
          Default:xhrdata = Xhr.responsetext;
        } _opts.success && _opts.success (XHRDATA,XHR);
        }else{_opts.error && _opts.error (XHR);
      } _opts.complete && _opts.complete (XHR);   
    }
    };
    Xhr.open (_opts.type,_opts.url,_opts.async); if (_opts.type.touppercase () = = = ' POST ') {xhr.setrequestheader (' content-type ', ' application/x-www-form-urlencoded ')
    ;
  } xhr.send (_opts.type.touppercase () = = ' Get ' Null:param (_opts.data)); } return {Ajax:ajax}}) ();

Define the parameter options to analyze. Where DataType is the focus of the entire Ajax, the code is simple or complex in it.

Here datatype the data types returned for the expected server: XML, HTML, text, JSON, JSONP, script

1. For XML, the response from the server is XML, using the Responsexml property to get the returned data

2. For HTML, text, and JSON, use the ResponseText property to get the returned data

A. Returns plain text HTML information when HTML is included, whether the script tag to be executed when inserting the DOM (Code complexity +3)

B. Returns JSON data for JSON to be secure, convenient, and compatible (code complexity +2)

3. For Jsonp, the general Cross-domain only use it, not the original Ajax request, with the creation of script (code complexity +2)

4. When the script: to cross the domain, do not use the original Ajax request, with the creation of script (code complexity +1), not cross-domain, return the plain text JavaScript code, use the ResponseText property to get the returned data (code complexity of +1)

The script tag, Jsonp, script in the HTML fragment is used to create the script label.

  Processing datatype as JSON

Xhrdata = window. JSON && windows. Json.parse? Json.parse (Xhr.responsetext): eval (' (' + xhr.responsetext + ') ');

This is the easiest way to do this, and for JSON compatibility, you can use Json2.js.

  Processing datatype for JSONP

JSONP is to request cross-domain through the script tag, first understand the following process:

The Http://www.b.com/b.php?callback=add (request URL is the link in the AJAX program) is a.html in the figure above, and the passed parameters are read in b.php Callback=add based on the parameter values obtained ( Value is add, the function name is generated in JS syntax, and the JSON data is passed into this function as a parameter, returning the document generated in JS syntax to a.html,a.html parsing and executing the returned JS document, invoking the defined add function.

A more general approach to calling in a program, such as the following widely used Loadjs function:

function Loadjs (URL, callback) {
  var doc = document, script = doc.createelement (' script '), BODY = Doc.getelementsbytag Name (' body ') [0];
  Script.type = ' text/javascript ';
  if (script.readystate) { 
    script.onreadystatechange = function () {
      if (script.readystate = = ' Loaded ' | | Script.readystate = = ' complete ') {
        script.onreadystatechange = null;
        Callback && callback ();
      }
  else { 
    script.onload = function () {
      callback && callback ();}
    ;
  }
  script.src = URL;
  Body.appendchild (script);

This puts the requested URL into the Loadjs function and gets the same result.

Copy Code code as follows:

Loadjs (' Http://www.b.com/b.php?callback=add ');

Because the script is created dynamically and the request returns successfully, the JS code executes immediately, and if the request fails there is no hint. Therefore, custom parameter options: _opts.success can be invoked, _opts.error cannot be invoked.

 Ajax processing JSONP also has two kinds of situations:

1. Set the request URL after the parameter Callback=add in particular defined the function name add, the request successfully returned, JS code immediately execute (here is call Add ({"A": 8, "B": 2}))

2. Processing JSON data in _opts.success is to request a successful return, the JS code does not execute, and the parameters in the function are moved out, as _opts.success parameter return (here is equivalent to processing string ' Add ({"A": 8, "B": 2}) ', remove ' Add (' and ') ', get {"A": 8, "B": 2})

  Processing datatype to HTML

If you do not process the script tag in the HTML fragment, insert the ResponseText return value directly into the DOM tree. If you want to deal with script, you need to find the script tags in the HTML fragment, to buy a script to deal with, and note that the script tag contains the JS code or through SRC request.

 Process datatype as Script

If you want to cross the domain, you can create the script in a way that is similar to working with JSONP, do not cross the domain, use the ResponseText property to get the returned data, use eval for code execution, or create a script to execute.

function Addjs (text) {
  var doc = document, script = doc.createelement (' script '), head = Doc.getelementsbytagname (' bod Y ') [0];
  Script.type = ' text/javascript ';
  Script.text = text;
  Body.appendchild (script);

By the end of this AJAX analysis, the actual need to add a variety of features to think about how each function is achieved, and can find a solution.

The above content is small to share with you do not use the library (framework) to write their own Ajax, I hope you like.

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.