Write Ajax yourself without a library (frame)

Source: Internet
Author: User
Tags html form unique id

It is common to use AJAX to request data, to load a library (framework), and perhaps just maybe to use its AJAX parts.

  write an Ajax, one that can go through The process of dealing with the problem, improve the technical ability, secondly, the work sometimes really does not need such a large library (framework), with their own writing, he le it.

Let's take a look at how popular jquery calls Ajax

$.ajax ({url: ' test.php ',//Send request URL String type: ' GET ',///Send As DataType: ' json ',//expected server return data type XML, HTML, text, JSON, JSONP, SC Riptdata: ' K=v&k=v ',//data sent async:true,//asynchronous request Cache:false,//cache timeout:5000,//time-out milliseconds beforesend:function () {},// Request before Error:function () {},//request error success:function () {},//request succeeds when Complete:function () {}//after request completes (regardless of success or failure)});

Such a call is not very comfortable, convenient, if you feel comfortable that your own writing also refer to this design method, not too complex, to meet the needs of the good .

  First the the basics of solving Ajax

  XMLHttpRequest Object

The XMLHttpRequest object is the core of Ajax, with XMLHttpRequest objects to send asynchronous requests to the server to get 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

send a request to the server

Xhr.open (Method,url,async);//method: type of request; GET or Post//url: url//async:true (asynchronous) or False (synchronous) Xhr.send (string) of the request;// Send request to Server//string: only for post requests//get is simpler and faster than post requests, and in most cases, use the POST request://cannot use the cache file (update the file or database on the server)// Send a large amount of data to the server (post no data limit)//send user input with unknown characters, post is more stable and more reliable than GET

  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 a response in the form of a string.

  onReadyStateChange Events

When a request is sent to the server, we need to perform some response-based tasks. The onreadystatechange event is triggered whenever the readyState changes. The ReadyState attribute holds state information for XMLHttpRequest.

Three important attributes of the XMLHttpRequest object:

    onreadystatechange //Store 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: Server Connection 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 defined the task performed when the server responds to readiness to be processed, and when readystate equals 4 and status is 200, the response is ready .

Xhr.onreadystatechange = function () {    if (xhr.readystate = = 4 && xhr.status = = 200) {//ready to handle returned xhr.respons EText 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 = = 200) {//ready to handle the returned Xhr.responsetext or Xhr.responsexml}};xhr.open (method,u Rl,async); Xhr.send (string);

Supplement: 1. The result of the cache may be obtained when a GET request is sent, and in order to avoid this, a unique ID, timestamp, can be added to the URL. 2. If you need to POST data like an HTML form, use setRequestHeader () to add an HTTP header. The data is then sent in the Send () method.

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

  Start writing your own Ajax

Write a basic, define various parameter options, for reference

var $ = (function () {///helper function serialization parameter function param (data) {//.} function Ajax (opts) {var _opts = {url: '/',//Send request URL address type: ' Get ',//Send Request way Get (default), Postdatatype: ',/    /expected server returned data type XML, HTML, text, JSON, JSONP, scriptdata:null,//sent data ' Key=value&key=value ', {key:value,key:value}  async:true,//Asynchronous request Ture (default async), Falsecache:true,//cache Ture (default cache), False timeout:5,//Timeout time default 5 seconds Load: function () {},//Request load in Error:function () {},//request error when success:function () {},//request succeeded Complete:function () {}//request completed After (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.indexof ('? ') < 0?        '? ': ' & ') + param (_opts.data); }        !_opts.cache && (_opts.url + = (_opts.url.indexof ('? ') < 0?    '? ': ' & ') + ' _= ' + (+new Date ()));  } function Checktimeout () {if (xhr.readystate!== 4) {aborted = True;xhr.abort (); }}settimeout (Checktimeout, _opts.timeout*1000); xhr.onreadystatechange = function () {if (xhr.readystate!== 4) _opts.lo    Ad && _opts.load (XHR);  if (xhr.readystate = = = 4) {var s = xhr.status, xhrdata;if (!aborted && (s >= && s < 300) | |    s = = = 304) {switch (_opts.datatype.tolowercase ()) {case ' xml ': Xhrdata = xhr.responsexml;    Break Case ' json ': xhrdata = window. JSON && window. 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 it. Where DataType is the focus of the entire Ajax, the code is simple or complex in it.

Here datatype the data type returned for the expected server:XML, HTML, text, json, Jsonp, script

1. when XML, the response from the server is XML, using the responsexml property to get the returned data

2. for HTML, text, JSON, use the responsetext property to get the returned data

A. When HTML, returns plain text HTML information that contains the script tag to be executed when inserting the DOM (Code complexity +3)

B. When JSON, return JSON data, be safe, easy, and compatible (code complexity +2)

  3. for JSONP, it is generally used across domains, without the original AJAX request, using the Create Script method (code complexity +2)

  4. for script: to cross the domain without the original AJAX request, use the Create Script method (code complexity +1); Do not cross-domain, return plain text JavaScript code, use responsetext Property gets the returned data (code complexity +1)

Where script tags, jsonp, and script in an HTML fragment are used to create a script tag.

  Processing datatype as JSON

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

This is the simplest way to handle it, and to be JSON compatible, you can use Json2.js.

  Handling datatype to Jsonp

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

In this a.html request Http://www.b.com/b.php?callback=add (in the AJAX program request URL is this link), in b.php read the passed parameters Callback=add based on the obtained parameter value (value is add), the JS syntax generated the function name, and the JSON data as a parameter passed to the function, return the JS syntax generated by the document to A.html, A.html parses and executes the returned JS document, invoking the defined add function.

In the program is generally used in a more general way to invoke, such as the following widely used Loadjs function:

function Loadjs (URL, callback) {var doc = document, script = doc.createelement (' script '), BODY = Doc.getelementsbytagname ( ' 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, passing in the Loadjs function, to get the same result.

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

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

  There are two situations in which Ajax handles JSONP:

1. set the parameters after the request URL callback=add specifically defines the function name add, the request returns successfully, the JS code executes immediately (this is called Add ({"A": 8, "B": 2}) )

2. in _opts.success, the JSON data is processed, that is, the request is returned successfully, the JS code is not executed, and the parameters in the function are removed and returned as _opts.success parameters (this is equivalent to processing the string 'Add ({"A": 8 , "B": 2}) ', remove ' Add (' and ') ', get {"A": 8, "B": 2} )

  Handling datatype as 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 are working with script, you will need to find the script tag in the HTML fragment, deal with the script separately, and note that the JS code contained in the script tag is requested by SRC.

  Handling datatype as Script

If you want to cross a domain, you can create a script that is similar to handling JSONP, do not cross-domain, use the ResponseText property to get the returned data, either by using eval for code execution, or by creating a script to execute.

function Addjs (text) {var doc = document, script = doc.createelement (' script '), head = Doc.getelementsbytagname (' body ') [0 ];script.type = ' Text/javascript '; script.text = text;body.appendchild (script);}

To this Ajax almost finished analysis, according to the actual needs, add a variety of functions, to consider how each function is implemented, and can find a solution.

If you are using an off-the-shelf library (framework), what progress does technology make?

Write Ajax yourself without a library (frame)

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.