Javascript native ajax writing _ javascript skills

Source: Internet
Author: User
This article uses two examples to share with you how and how native javascript uses ajax to implement data requests. It is very simple and practical. If you need it, you can refer to ajax: a Data Request Method. You do not need to refresh the entire page;
The core of ajax is the XMLHttpRequest object;
Ajax request process: Create an XMLHttpRequest object, connect to the server, send requests, and receive response data;

/*** Get ajax object */function getajaxHttp () {var xmlHttp; try {// chrome, Firefox, Opera 8.0 +, Safari xmlHttp = new XMLHttpRequest ();} catch (e) {// Internet Explorer try {// IE5, 6 xmlHttp = new ActiveXObject ("Msxml2.XMLHTTP");} catch (e) {try {// xmlHttp = new ActiveXObject ("Microsoft. XMLHTTP ");} catch (e) {alert (" your browser does not support AJAX! "); Return false ;}}return xmlHttp;}/*** send ajax Request * url -- url * methodtype (post/get) * con (true (asynchronous) | false (synchronous) * parameter (parameter) * functionName (callback method name, which is called only when the callback method is successful without quotation marks) * (note: this method has two parameters: xmlhttp and the object to be processed.) * obj is the object to be processed in the callback Method */function ajaxrequest (url, methodtype, con, parameter, functionName, obj) {var xmlhttp = getajaxHttp (); xmlhttp. onreadystatechange = function () {// readyState value description // 0, initialization, XHR object created, open // 1 not executed, load, open method called, but no request has been sent // 2, the load is complete, the request has been sent // 3, interaction, some data can be received // status description // 200: success // 404: No file, query, or URl found // 500: the server generates an internal error if (xmlhttp. readyState = 4 & XHR. status = 200) {// The functionName (xmlhttp, obj) ;}; xmlhttp. open (methodtype, url, con); xmlhttp. send (parameter);} // This is the parameter function createxml () {var xml ="
 
  
   
Asdfasdfasdf <\/userid> <\/user> "; //" \/"this is not an uppercase V, but the escape is a left slash and a right slash return xml ;} // This is the Parameter function createjson () {var json = {id: 0, username: ""}; return json;} function c () {alert ("");}
  
 

// Test

ajaxrequest("http://www.baidu.com","post",true,createxml(),c,document);

Let's look at an example.

Ajax ({url :". /TestXHR. aspx ", // request address type:" POST ", // Request Method data: {name:" super ", age: 20}, // request parameter dataType: "json", success: function (response, xml) {// code executed after the operation is successful}, fail: function (status) {// code executed after the failure is put here}); function ajax (options) {options = options |{}; options. type = (options. type | "GET "). toUpperCase (); options. dataType = options. dataType | "json"; var params = formatParams (option S. data); // create-non-IE6-Step 1 if (window. XMLHttpRequest) {var xhr = new XMLHttpRequest ();} else {// IE6 and earlier browsers var xhr = new ActiveXObject ('Microsoft. XMLHTTP ');} // receive-Step 3 xhr. onreadystatechange = function () {if (xhr. readyState = 4) {var status = xhr. status; if (status> = 200 & status <300) {options. success & options. success (xhr. responseText, xhr. responseXML);} else {options. fail & o Ptions. fail (status) ;}}// connect and send-Step 2 if (options. type = "GET") {xhr. open ("GET", options. url + "? "+ Params, true); xhr. send (null);} else if (options. type = "POST") {xhr. open ("POST", options. url, true); // sets the content type xhr when the form is submitted. setRequestHeader ("Content-Type", "application/x-www-form-urlencoded"); xhr. send (params) ;}}// the formatting Parameter function formatParams (data) {var arr = []; for (var name in data) {arr. push (encodeURIComponent (name) + "=" + encodeURIComponent (data [name]);} arr. push ("v =" + Math. random ()). replace (". "," "); return arr. join ("&");}

Let's look at the principle.

1. Create

1.1. IE7 and later versions support native XHR objects, so you can directly use: var oAjax = new XMLHttpRequest ();

1.2. in IE6 and earlier versions, XHR objects are implemented through an ActiveX object in the MSXML library. Some books detail three different versions of such objects in IE, namely, MSXML2.XMLHttp and MSXML2.XMLHttp. 3.0 and MSXML2.XMLHttp. 6.0. In my personal experience, you can directly use the following statement to create var oAjax = new ActiveXObject ('Microsoft. XMLHTTP ');

2. Connect and send

2.1. Three parameters of the open () function: Request Method, request address, and asynchronous request (the synchronous request is rare and has never been used yet );

2.2. the GET request uses the URL parameter to submit data to the server, and the post request uses the data as the send parameter to submit the data to the server;

2.3 In the POST request, you must set the content type for form submission before sending data;

2.4 The parameters submitted to the server must be encoded by the encodeURIComponent () method. In fact, both the key and value must be encoded in the form of "key = value" in the parameter list, because it contains special characters. A "v = xx" string is added to the parameter list for each request. In this way, the request is directly sent to the server to reject the cache.

EncodeURI (): used to encode the entire URI. It does not encode special characters belonging to the URI, such as the colon, forward slash, question mark, and well number. Its corresponding decoding function decodeURI ();
EncodeURIComponent (): used to encode a part of the URI and encode any non-standard characters it discovers. Its decoding function is decodeURIComponent ();

3. Receive

3.1 after a response is received, the response data is automatically filled with the XHR object. The related attributes are as follows:
ResponseText: Body content returned by the response, which is of the string type;
ResponseXML: If the response content type is "text/xml" or "application/xml", the corresponding xml data is saved in this attribute, which is the document type corresponding to XML;
Status: the HTTP status code of the response;
StatusText: HTTP status description;

3.2 The readyState attribute of the XHR object indicates the current active phase of the Request/response process. The value of this attribute is as follows:
0-not initialized. The open () method has not been called;
1-start, the open () method is called, and the send () method is not called;
2-send. The send () method has been called and no response has been received;
3-received, some response data has been received;
4-complete. All response data has been received;

As long as the value of readyState changes, the readystatechange event will be called. (In fact, to be logically smooth, you can put readystatechange after sending. Because network communication is required when sending requests to the server, it takes time, it is also possible to specify the readystatechange event handler after sending, which is usually used in this way, but to standardize compatibility with cross-browser, you should specify it before open ).

3.3 In the readystatechange event, determine whether the response is received and whether the server successfully processes the request. xhr. status indicates the status code. If the status code starts with 2, it is successful. 304 indicates that it is obtained from the cache. The preceding Code adds a random number to each request, therefore, it does not take values from the cache, so this status does not need to be determined.

4. ajax requests cannot be cross-origin!

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.