Cross-origin asynchronous request 1

Source: Internet
Author: User

I have always wanted to build a powerful asynchronous system, but it is more complicated to implement various browsers in this regard, coupled with cross-origin requirements. Now I can write down all the things that I can think of for the time being.

First, determine the parameter. It looks like gm_xmlhttprequest of greasemonkey.

 
Dom. ajax ({method: "Get", // HTTP request type, get post Delete put URL: location. href, // must be the absolute path headers: {"Content-Type": "application/X-WWW-form-urlencoded"}, // header, object literal overridemimetype: "text/html; charset = ISO-8859-1", data: NULL, // The onerror: function () {}, // The callback function onload when a request error occurs: function () {}// callback function when the request is successful });

Then it is implemented internally. Cross-origin is not considered for the time being. It looks like this:

Dom. ajax = function (OPTs) {var S = Dom. mixin (true, {}, Dom. ajaxsettings, opts), method = S. method. touppercase (), xhr = Dom. xhr (); If (S. username) {xhr. open (method, S. URL, S. async, S. username, S. password);} else {xhr. open (method, S. URL, S. async);} xhr. setRequestHeader ("X-requested-with", "XMLHttpRequest"); xhr. onreadystatechange = function () {If (xhr. readystate = 4) {// alert (xhr. responsetext) }}; xhr. send (OPTs. data | null );}

The next step is to strengthen various details, such as processing the transmitted data, adding parameters to the URL, cache settings, and header settings ......

Generally, when submitting a form, the name and value of the form element are converted to "name1 = value1? Name2 = value2 ". If it is a POST request, it is put in the send method. If it is a get method, it is placed after the URL. In addition, if the method is not get or post, we need to use post to simulate it. Sometimes, we add data with special identifiers for requests, such as query services (IP queries, RSS subscriptions, and weather forecasts) for large companies ). In order to put the processing object, we need to convert it into an object, and then change it back to the string when sending the request:

Query = Dom. isstring (obj. Data )? Dom. ajax. toqueryobject (obj. data): obj. data | {} If (/get | post/I. test (method) {query. _ method = method; method = obj. method = "Post"} query = Dom. ajax. toquerystring (query)

Cache processing. If it is a test phase, we can set the first if-modified-since to 0. For GET requests, we can also add a time cut or a random number.

First, it must be called before the open method can be used:

Setrequestheaders: function (xhr, OBJ) {// Ajax object and parameter object var headers = {"accept": obj. Accepts [obj. datatype]? OBJ. Accepts [obj. datatype] + ", */*": obj. Accepts. _ default, "x-requested-with": "XMLHttpRequest"} If (! OBJ. cache) {headers ["If-modified-since"] = "0"} Dom. mixin (headers, obj. headers) if (obj. method = 'post') {headers ['content-type'] = obj. contenttype + '; charset =' + obj. encoding; If (xhr. overridemimetype & (navigator. useragent. match (/gecko \/(\ D {4})/) | [0, 2005]) [1]

Timeout and abort processing, because the two methods have different levels of support in different browsers, the best thing to do is IE8 xdomainrequest and XMLHttpRequest.

VaR xhr = Dom. xhr (); xhr. open ("Post", location. href, true); xhr. onreadystatechange = function () {If (xhr. readystate = 4 & xhr. status = 200) {cleartimeout (xhrtimeout); alert (xhr. responsetext) ;}} xhr. send ("Ruby Louvre"); var xhrtimeout = setTimeout ("ajaxtimeout ();", 5000); function ajaxtimeout () {xhr. abort (); alert ("force close link! ");}

However, to be compatible with all browsers, the cheapest method is jsonp. For details, refer to this article.Article: Zookeeper communication method zookeeper Communication Method

 function jsonp (URL, callback, name, query) {If (URL. indexof ("? ")! =-1) URL + = "& jsonp =" else URL + = "? Jsonp = "url + = Name +" & "; if (query) URL + = encodeuricomponent (query) +" & "; Url + = (new date-0 ); // prevent caching var script = document. createelement ("script"); script. setattribute ("src", URL); script. setattribute ("type", "text/JavaScript"); document. body. appendchild (SCRIPT) ;}

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.