Simple Introduction: Do not use libraries (frameworks) to write ajax by yourself. A brief introduction to ajax

Source: Internet
Author: User

Simple Introduction: Do not use libraries (frameworks) to write ajax by yourself. A brief introduction to ajax

Usually, ajax is used to request data, load a library (framework), and perhaps only maybe uses its ajax part.

To write ajax, you can go through the process of solving problems and improve technical capabilities. Second, sometimes you don't need such a large library (framework) in your work, so you can't do it yourself.

Let's take a look at how popular jQuery calls ajax.

$. Ajax ({url: 'test. php ', // The type of the URL string for sending the request: 'get', // The sending method dataType: 'json', // the Data type xml, html, text, json, jsonp, script data: 'K = v & k = V', // send data async: true, // asynchronous request cache: false, // cache timeout: 5000, // timeout time millisecond beforeSend: function () {}, // error before request: function () {}, // success: function () {} when a request error occurs (){}, // when the request is successful, complete: function () {}// after the request is completed (whether successful or failed )});

This call is not very comfortable and convenient. If you feel comfortable, you can also refer to this design method by yourself. It is not too complicated to meet your needs.

First understand the basic ajax knowledge

XMLHttpRequest object

XMLHttpRequest objects are the core of ajax. XMLHttpRequest objects are used to send asynchronous requests to the server to obtain data from the server. All modern browsers (IE7 +, Firefox, Chrome, Safari, and Opera) both support XMLHttpRequest objects (IE5 and IE6 use ActiveXObject ).

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: Request type; GET or POST
// Url: the requested URL
// Async: true (asynchronous) or false (synchronous)
Xhr. send (string );
// Send the request to the server
// String: used only for POST requests
// GET is simpler and faster than the POST request method, and can be used in most cases
// Use the POST request in the following cases:
// Unable to use cached files (updating files or databases on the server)
// Send a large amount of data to the server (there is no limit on the size of POST data)
// When sending user input containing unknown characters, POST is more stable and reliable than GET.

Server Response

Use the responseText or responseXML attribute of the XMLHttpRequest object to obtain the response from the server.

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

If the response from the server is not XML, use the responseText attribute and the responseText attribute to return a string response.

Onreadystatechange event

When a request is sent to the server, we need to execute some response-based tasks. When the readyState changes, the onreadystatechange event is triggered. The readyState attribute contains the status information of XMLHttpRequest.

  Three important attributes of the XMLHttpRequest object:

    Onreadystatechange// Storage function (or function name). This function is called whenever the readyState attribute changes.

    ReadyState// The XMLHttpRequest status changes from 0 to 4.

0: the request is not initialized.
1: The server connection has been established.
2: The request has been received
3: The request is being processed
4: The request is complete and the response is ready.

    Status// 200: "OK", 404: Page not found

In the onreadystatechange event, we stipulate that when the server responds to a task that is ready for processing, when readyState is 4 and status is 200, the response is ready.

Xhr. onreadystatechange = function () {if (xhr. readyState = 4 & xhr. status = 200) {// ready to process the returned xhr. responseText 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 process the returned xhr. responseText or xhr. responseXML }}; xhr. open (method, url, async); xhr. send (string );

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

url += (url.indexOf('?') < 0 ? '?' : '&') + '_='+ (+new Date());xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

  Start writing your own ajax

First, write a basic and define various Parameter options for your reference.

Var $ = (function () {// auxiliary function serialization Parameter function param (data ){//..} function ajax (opts) {var _ opts = {url: '/', // send request URL type: 'get', // send request method GET (default ), POST dataType: '', // expected data types returned by the server: xml, html, text, json, jsonp, script data: null, // send data 'key = value & key = value', {key: value, key: value} async: true, // asynchronous request ture (asynchronous by default ), false cache: true, // cache ture (default cache), false timeout: 5, // default timeout value: 5 seconds load: f Unction () {}, // error: function () {}during request loading, // success: function () {}when an error occurs in the request, // complete when the request is successful: function () {}// after the request is completed (whether successful or failed)}, 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. load & _ opts. load (xhr); if (xhr. readyState = 4) {var s = xhr. status, xhrdata; if (! Aborted & (s> = 200 & 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 }})();

The Parameter options are defined for analysis. DataType is the focus of ajax, and its code is simple or complicated.

Here, dataType is the data type returned by the expected server: xml, html, text, json, jsonp, script

1. When xml is used, the response from the server is XML and the returned data is obtained using the responseXML attribute.

2. When it is html, text, or json, use the responseText attribute to retrieve the returned data.

A. When it is html, the plain text HTML information is returned. Whether the script tag contained in the tag should be executed when the dom is inserted (Code complexity + 3)

B. When json is returned, JSON data must be secure, convenient, and compatible (Code complexity + 2)

3. When jsonp is used, it is generally used for cross-origin requests. The original ajax request is not used and the script Creation method is used (Code complexity + 2)

4. when it is a script: When cross-origin is required, the original ajax request is not used, and the script method is created (Code complexity + 1). If it is not cross-origin, the plain text JavaScript code is returned, use the responseText attribute to get the returned data (Code complexity + 1)

The script tag, jsonp, and script in the html fragment must all be created using the script TAG method.

Processing dataType as json

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

This is the simplest processing method. To be JSON compatible, you can use json2.js.

Processing dataType as jsonp

Jsonp uses the script tag to request cross-origin requests. First, let's take a look at the following process:

Which a.html requested the http://www. B .com/ B .php? Callback = add (the url requested in the ajax program is the link), in B. php reads the passed parameter callback = add callback to parse and execute the returned JS document, and calls the defined add function.

Generally, a more general method is used to call a program. For example, 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);}

In this way, the request url is passed into the loadJS function and the same result is obtained.

Copy codeThe Code is as follows:
LoadJS ('HTTP: // www. B .com/ B .php? Callback = add ');

Because the script is created dynamically and the request is returned successfully, the JS code is executed immediately. If the request fails, there is no prompt. Therefore, the custom Parameter options: _ opts. success can be called, and _ opts. error cannot be called.

 There are two scenarios for ajax to process jsonp:

1. the parameter callback = add after the request URL is set. In particular, the function name add is defined. If the request is returned successfully, the JS code is executed immediately (here, add ({"a": 8, "B": 2 }))

2. in _ opts. processing JSON data in success means that the request is returned successfully, JS Code is not executed, and parameters in the function are removed as _ opts. success parameter return (here is equivalent to processing the string 'add ({"a": 8, "B": 2}) ', remove 'add (' and ')', {"a": 8, "B": 2 })

Process dataType as html

If you do not process the script tag in an HTML clip, simply insert the responseText return value into the DOM tree. If you want to process the script, you need to find the script tag in the HTML segment and separately process the script. Note that the JS Code contained in the script tag is still requested through src.

Process script ype as script

If you want to create a script in cross-origin mode, it is similar to processing jsonp. If you do not use cross-origin, you can use the responseText attribute to obtain the returned data and use eval for code execution, you can also create a script for execution.

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);}

By now, ajax has almost been analyzed. Based on actual needs, you can add various functions to think about how each function is implemented and find a solution.

The above content is what I want to share with you. I hope you will like it if you do not need to write ajax in libraries (frameworks.

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.