Ajax techniques in JavaScript and jquery "include various Cross-domain technologies for Ajax" _javascript tips

Source: Internet
Author: User
Tags script tag

The examples in this article describe Ajax techniques in JavaScript and jquery. Share to everyone for your reference, specific as follows:

1. What is Ajax?

Ajax, "Asynchronous JavaScript and XML" (Asynchronous JavaScript and XML), refers to a web development technology that creates interactive Web applications.

AJAX enables asynchronous updating of Web pages by making a small amount of data exchange in the background with the server. This means you can update portions of a Web page without reloading the entire page.

Traditional Web pages (without AJAX) if you need to update the content, you must overload the entire page page.

Realization of 2.AJAX in native JS

Although with the popularity of JS framework, in jquery, the implementation of Ajax process is quite simple, but for some do not need to load jquery such a large plug-in project, or to adopt the original AJAX implementation!

To achieve the native JS Ajax process, for the high version of the browser, support JS XMLHttpRequest object, and the lower version of the browser ie6,ie7 incompatible, so to use the ActiveXObject () object to implement, The XMLHttpRequest objects that are compatible with each version are built as follows:

var xml;
if (window. XMLHttpRequest)
{
  xml=new xmlhttprequest ();
}
else{
  xml=new ActiveXObject ("Microsoft.XMLHTTP");
}

There are a number of ways to XMLHttpRequest objects,

(1) Xml.readystate: Indicates the state of the request where xml.readystate=0 represents the preparation phase of the request, xml.readystate=1, indicates that the request was started, xml.readystate=2 that the server has received the request, Xml.readystate=3 indicates that the server is processing the request, xml.readystate=4 indicates that the server has processed the request and returned the request to the client.

0-(uninitialized) the Send () method has not been called
1-(load) called Send () method, sending request
2-(load complete) Send () method completed, received all response content
3-(interactive) parsing response content
4-(complete) The response content resolution is complete and can be invoked on the client

(2) Xml.status: Indicates the status description in the request process,

1XX Information Tip:

These status codes represent a temporary response. The client should be prepared to receive one or more 1xx responses before receiving a regular response.

2XX indicates success,

3XX redirect

The client browser must take more action to implement the request. For example, a browser might have to request a different page on the server, or repeat the request through a proxy server.

4XX Client Error

An error occurred and the client appears to have a problem. For example, a client requests a page that does not exist, and the client does not provide valid authentication information.

5XX Server Error

The server was unable to complete the request due to an error encountered.

(3) To implement the GET request in Ajax using native JS:

var xml=new xmlhttprequest ();
Xml.onreadystatechange=function () {
 if (xml.readystate==4&&xml.status==200)
 {
   var data= Json.parse (Xml.responsetext);
  }
  else{
   alert ("Request Failed");
  }
Xml.open ("Get", "url", "true");//url inside for the requested address, True indicates the asynchronous request
Xml.send (NULL)

(4) Using native JS to implement POST request:

var xml=new xmlhttprequest ();
Xml.onreadystatechange=function () {
 if (xml.readystate==4&&xml.status==200)
 {
   var data= Json.parse (Xml.responsetext);
 }
 else{
   alert ("Request Failed");
 }
Xml.open ("Post", "url", "true");//url inside for the requested address, True indicates the asynchronous request
Xml.setrequestheader ("Content-type", "application/ X-www-form-urlencoded "); Set Request header
Xml.send (NULL) for POST requests

Why to set request header information:

By default, Ajax submits data in a content-type:text/plain manner, and the server ignores the data in the Post entity section, so the server cannot get the data from the POST request.

Workaround:

content-type:application/x-www-form-urlencoded

Cross-domain technology in 3.AJAX

(1). Cross-domain Way There is the first proxy access. <script></script> This method can access JS files across domains, such as

<script src= "Www.abc.com/de.php?callback=dosomething" </script>

Just like the introduction of JS, but the difference is that the JSONP approach requires server-side language coordination across domains.

(2). A Jsonp method that can only be used for a Get method, spanning a domain such as we have

Datatype:jsonp
Jsonp:callback

Then add the background processing can! ~

(3). Using the XHR2 method, operate in the background to achieve Cross-domain support IE9 above such as header ("access-control-allow-origin:*"); Header (" Access-control-allow-methods:post,get "); You can implement Cross-domain, and we will have the address source in the * that allows Cross-domain addresses! ~

(4). Document.domain to cross Domain

Document.domain in an IFRAME that needs to be cross-domain, plus the same document.domain,xxx.com

4. The following main introduction to JSONP and Cors access solutions

(1) First for JSONP Cross-domain: Because Ajax itself is not cross-domain, there is a homologous protection policy, but the label with SRC can cross domain

such as <script> and tags, you can implement Cross-domain request, here is mainly introduced in jquery Jsonp method of Cross-domain implementation:

Jsonp of the realization of the idea:

1. Front end Create script tag, set SRC, add to head (you can add to body)

2. Background returns a JS variable Jsonp, this JSONP is the JSON data after the request

3. Delete the script tag after the callback completes (there are some cleanup work such as avoiding some browser memory leaks, etc.)

$.ajax ({
 type: "Get",
 async:false,
 URL: "Ajax.ashx",
 dataType: "Jsonp",
 jsonp: "Callbackparam" ,//passed to the request handler or page
 jsonpcallback: "Success_jsonpcallback",//Custom JSONP callback function name
 success:function (JSON) {
 alert (JSON);
 alert (json[0].name);
 },
})

(2) Cors cross-domain method

Cors defines a cross-domain access mechanism that enables Cross-domain access for Ajax, Cors allows network applications on one domain to submit Cross-domain access requests to another domain, which is simple enough to send a corresponding request to the server! For example, in PHP, you can write:

Header ("access-control-allow-origin:*");
Header ("Access-control-allow-methods:post,get")

Implemented in the XHR2 method, and for IE, only IE9 above browsers are supported

More readers interested in JavaScript-related content can view this site: "JavaScript Ajax Operating Skills Summary", "JavaScript switching effects and techniques summary", "JavaScript Search Algorithm Skills summary", " JavaScript animation effects and tips Summary, "JavaScript Error and debugging skills Summary", "JavaScript data structure and algorithm skills summary", "JavaScript traversal algorithm and Skills summary" and "JavaScript Mathematical operation Usage Summary"

I hope this article will help you with JavaScript programming.

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.