Native JavaScript for AJAX, JSONP

Source: Internet
Author: User
Tags script tag

It is believed that most front-end developers, when they need to interact with the backend, will choose the method of encapsulation in order to be quick and easy, JQuery AJAX but there are times when we only need JQuery the AJAX request method, and the other functions are seldom used, which is obviously unnecessary.
In fact, the native JavaScript implementation AJAX is not difficult, this article will explain how to achieve simple AJAX , as well as cross-domain requests JSONP !
First, AJAX
The core of Ajax is XMLHttpRequest .
A complete AJAX request typically consists of the following steps:

    • Instantiating an XMLHttpRequest object
    • Connecting to a server
    • Send Request
    • Receive response data


I AJAX encapsulate the request into ajax() a method, which accepts a configuration object params .

function Ajax (params) {params = params | |  {}; Params.data = Params.data | |  {}; Is it an AJAX request or a JSONP request var json = Params.jsonp?  JSONP (params): JSON (params); Ajax request function JSON (params) {///request mode, default is Get Params.type = (Params.type | |  ' GET '). toUpperCase ();   Avoid having special characters, you must format the transmitted data Params.data = Formatparams (Params.data); var xhr = null;
Instantiate the XMLHttpRequest Object if (window. XMLHttpRequest) {xhr = new XMLHttpRequest (); } else {//IE6 and the following version xhr = new Activexobjcet (' microsoft.xmlhttp '); };
The listener event, as long as the value of the readyState changes, calls the ReadyStateChange event Xhr.onreadystatechange = function () {///ReadyState attribute represents the time when the request/response process Pre-active phase, 4 for completion, has received all response data if (xhr.readystate = = 4) {var status = Xhr.status; Status: The HTTP status code of the response, beginning with 2, is successful if (status >= && status <) {var response = '; Determine the content type of the accepted data var type = Xhr.getresponseheader (' Content-type '); if (type.indexof (' xml ')!==-1 && xhr.responsexml) {response = Xhr.responsexml;//document Object Response} else I F (Type = = = ' Application/json ') {response = Json.parse (xhr.responsetext);//json response} else {response = XH R.responsetext; String response}; Successful callback function params.success && params.success (response); } else {Params.error && params.error (status); } }; }; Connect and transmit data if (Params.type = = ' Get ') {//Three parameters: The request method, the request address (when the transfer data is added to the address), the asynchronous request (the situation of the synchronization request is very small); Xhr.open (Params.type, Params.url + '? ' + Params.data, true); Xhr.send (null); } else {Xhr.open (Params.type, Params.url, true); must, set the content type at the time of submission Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded; Charset=utf-8 '); Transmission Data Xhr.send (params.data); }}//format parameter function formatparams (data) {var arr = []; for (var name in data) {//encodeURIComponent (): Used to encode a portion of a URI Arr.push (encodeuricomponent (name) + ' = ' + encodeur IComponent (Data[name])); }; Add a random number parameter to prevent cache Arr.push (' v= ' + random ()); Return Arr.join (' & '); }

Gets the random number function random () {return Math.floor (math.random () * 10000 + 500); }
}

In the code above, specific comments have been added, for more information AJAX , see the chapters in the blogger's book, "Half-knowledge of JavaScript" AJAX : AJAX
Usage examples:

ajax({  url: ‘test.php‘,  // 请求地址 type: ‘POST‘,  // 请求类型,默认"GET",还可以是"POST" data: {‘b‘: ‘异步请求‘},  // 传输数据 success: function(res){  // 请求成功的回调函数  console.log(JSON.parse(res));  }, error: function(error) {}  // 请求失败的回调函数});


Second, JSONP
Homologous policy
Ajax needs "cross-domain", the culprit is the browser 同源策略 . That is, the Ajax of a page can only get data from the same source or the same domain as the page. How to call "homology" or "Same domain"? -- 协议、域名、端口号都必须相同 . For example:

http://example.com  和  https://example.com 不同,因为协议不同; http://localhost:8080  和  http://localhost:1000 不同,因为端口不同; http://localhost:8080  和  https://example.com 不同,协议、域名、端口号都不同,根本不是一家的。

When cross-domain requests, you will generally see this error:   XMLHttpRequest cannot load http://ghmagical.com/article/?intro=jsonp%E8%AF%B7%E6 %b1%82&v=5520. No ' Access-control-allow-origin ' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access.

How do I cross-domain requests? At this time, Jsonp on the debut!  
JSONP (JSON with Padding)   is a cross-domain request method. The main principle is to use the script  tag to cross-domain The requested attribute, by its   src   Properties send request to server, server returns &NBSP; javascript  code, the browser accepts the response, and then executes it directly, as it does with the   script   tag references the external file in the same principle. The

Jsonp consists of two parts: the callback function and the data , which is typically in the browser control and is sent as a parameter to the server side (of course, you can also fix the name of the callback function, But the name of the client and server side must be the same). When the server responds, the server will put the function and the data back into a string.  
Jsonp the request process:

    • Request phase: The browser creates a script label and assigns it a src value (similar http://example.com/api/?callback=jsonpCallback ).
    • Send request: When assigned script src , the browser initiates a request.
    • Data response: The server will return 数据 as a parameter and 函数名称 stitch together (formatted like " jsonpCallback({name: ‘abc‘}) ") to return. When the browser receives the response data, because the request is initiated script , it is equivalent to calling the jsonpCallback method directly and passing in a parameter.


For JQuery the JSONP request, here is not much to say, before also wrote an article "jquery Ajax request cross-domain problem."
Here's how to make it work with native students JavaScript .
is still the ajax() method to add Jsonp, the latter will be integrated together, JSONP configuration parameters are more than one jsonp parameter, it is your callback function name.

function Ajax (params) {params = params | |      {}; Params.data = Params.data | |      {}; var json = Params.jsonp? JSONP (params): JSON (params);
JSONP Request function Jsonp (params) {//Create a script tag and add to the page var callbackname = Params.jsonp; var head = document.getElementsByTagName (' head ') [0]; Sets the name of the callback parameter passed to the background params.data[' callback '] = Callbackname; var data = Formatparams (Params.data); var script = document.createelement (' script '); Head.appendchild (script); Create JSONP callback function Window[callbackname] = function (JSON) {head.removechild (script); Cleartimeout (Script.timer); Window[callbackname] = null; Params.success && params.success (JSON); };
Send Request SCRIPT.SRC = Params.url + '? ' + data;
To know if the request was successful, set the timeout to handle if (params.time) {Script.timer = SetTimeout (function () {Window[callbackname] = n Ull Head.removechild (script); Params.error && params.error ({message: ' timeout '}); }, time); } };
Format parameter function formatparams (data) {var arr = []; for (var name in data) {Arr.push (encodeURIComponent (name) + ' = ' + encodeURIComponent (Data[name])); };
Add a random number to prevent cache Arr.push (' v= ' + random ()); Return Arr.join (' & '); }
Gets the random number function random () {return Math.floor (math.random () * 10000 + 500); }}

Note : Since the script label's  src properties only function at the time of the first setting, the script label cannot be reused, so it should be removed after each completion of the operation;
Usage examples:

ajax({      url: ‘test.php‘,  // 请求地址     jsonp: ‘jsonpCallback‘, // 采用jsonp请求,且回调函数名为"jsonpCallbak",可以设置为合法的字符串     data: {‘b‘: ‘异步请求‘},  // 传输数据     success:function(res){  // 请求成功的回调函数      console.log(res);      },     error: function(error) {}  // 请求失败的回调函数    });

In the background using PHP processing:

<?php     $data = array(‘type‘=>‘jsonp‘);     $callback = isset($_GET[‘callback‘]) ? trim($_GET[‘callback‘]) : ‘‘;      echo $callback.‘(‘.json_encode($data).‘)‘;

Note : Do not miss the return with the function name and data stitching.
Of course, as I said earlier, you can give a fixed callback function name:

function jsonpCallback() {}    
<?php echo ‘jsonpCallback(‘.$data.


Finally I have merged with the AJAX JSONP request, download link: ajax.zip

Native JavaScript for AJAX, JSONP

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.