Home > Web Front-end > JS Tutorial > body text

Detailed explanation of AJAX mechanism and cross-domain communication

亚连
Release: 2018-05-25 11:42:22
Original
1608 people have browsed it

In a project I recently worked on, I needed ajax to obtain data across domains. There was a slight error in the process, so I reviewed ajax, recorded the key points about cross-domain issues, and shared them with everyone

1.Ajax

1.1. Introduction to Ajax
Introduction to Ajax In this part, we mainly talk about the origin of ajax. What is ajax? Because these have nothing to do with technology. Therefore, most of the details are mentioned in one stroke.

The origin of Ajax?

The term Ajax originated from an article titled "Ajax: A new Approach to Web Applications" published by Jesse James Garrett in 2005. In this article, he introduced a new technology, in his words Say, it is Ajax: the abbreviation of Asynchronous JavaScript XML.

What is Ajax?

The main purpose of this new technology is to enable the front-end web page to request additional data from the server without unloading the page. Since the emergence of this technology, Microsoft took the lead in introducing the XHRt object (the core object that Ajax can implement), and then other browsers have implemented this technology one after another. All in all, ajax is a technology that enables asynchronous communication.

1.2. The core object of Ajax---XMLHttpRequest
Because IE5 was the first to introduce this XHR object, there was no de facto standard at the time. There are three different XHR object versions in IE: MSXML2. ##

function createXHR() { //IE7之前的版本通过这种方式
  var versions = [
    'MSXML2.XMLHttp',
    'MSXML2.XMLHttp.3.0',
    'MSXML2.XMLHttp.6.0'
  ];
  var xhr = null;
  for (var item in versions) {
    try {
      xhr = new ActiveXObject(item); //若不存在该版本,可能会出错
      if (xhr) break;
    } catch (e) {
      //一般对这种错误不做处理
    }
  }
  return xhr;
}
Copy after login

After IE introduced this object, other browser manufacturers also followed suit. At this time, the XHR object became the de facto standard!

Create XHR objects across browsers;

function createXHttpRequest() {
  if (typeof XMLHttpRequest !== 'undefined') { //不要用 if(XMLHttpRequest){}这种形式,
    return new XMLHttpRequest();              //如果是这种形式在找不到XMLHttpRequest函数的情况下,会报错。
} else if (typeof ActiveXObject !== 'undefined') { 
         return createXHR(); //用到刚才我们创建的函数 
  } else { throw new Error('不能创建XMLHttpRequest对象'); } }
Copy after login
1.2. Usage of XMLHttpRequestThe XMLHttpRequest object has 6 functions:

open("method",url,boolean);
              //该方法的三个参数,分别为----提交方式"get"或者"post"等 
                //&& url是相对于执行代码的当前页面的路径(使用绝对路径是允许的)&&是否异步 
send();    
           //这个方法接收一个参数,这个参数是作为请求主体发送的数据, 
           //说明: 如果有参数,请使用post方式提交 使用方式如下,send("user="+username+"&pwd="+password);
           //如果没有参数,为了兼容性考虑,必须在参数中传入null,即send(null);该方式使用get方式提交

abort();       //取消当前响应,关闭连接并且结束任何未决的网络活动。

          //这个方法把 XMLHttpRequest 对象重置为 readyState 为 0 的状态,并且取消所有未决             //的网络活动。例如,如果请求用了太长时间,而且响应不再必要的时候,可以调用这个方法。

getResponseHeader()   

          //返回指定的 HTTP 响应头部的值。其参数是要返回的 HTTP 响应头部的名称。可以使用任             //何大小写来制定这个头部名字,和响应头部的比较是不区分大小写的。

          //该方法的返回值是指定的 HTTP 响应头部的值,如果没有接收到这个头部或者 readyStat             //e 小于 3 则为空字符串。如果接收到多个有指定名称的头部,这个头部的值被连接起来并             //返回,使用逗号和空格分隔开各个头部的值。

getAllResponseHeaders()       

          //把 HTTP 响应头部作为未解析的字符串返回。

          //如果 readyState 小于 3,这个方法返回 null。否则,它返回服务器发送的所有 HTTP 响应的

          //头部。头部作为单个的字符串返回,一行一个头部。每行用换行符 "\r\n" 隔开。

setRequestHeader()

         //向一个打开但未发送的请求设置或添加一个 HTTP 请求。
Copy after login

XMLHttpRequest There are 5 attributes of the object:

Attribute Description

responseText The text returned as the response subject

responseXML If the response is text/html or application/xml type, this attribute will be saved The response XML document

status http response status code
statusText http status description
readyState The status bits of the XMLHttpRequest object are 0 1 2 3 4 representing 5 states respectively
timeout Set the timeout time, the unit is ms. Currently only supported by IE8---not yet standardized (not recommended)

The event attribute onReadyStateChange of the XMLHttpRequest object: -----compatible with all browsers

This property listens to XMLHttpRequest Changes in the readyState property of the object:

Changes in readyState correspond to the following states:

0: Not yet initialized. Before calling open()

1: Start. After calling open(), but send() is not called;

2: Send. Called send() but got no response yet.

3: Receiving data. From the moment the response data is received to the time the reception is completed.

4: Complete. Data reception completed.

xhr.onreadystatechange = function () {
 if (xhr.readyState == 4) {
  if (xhr.status >= 200 && xhr.status <== 300 || xhr.status == 304) {
   alert(xhr.responseText);
   //处理接收的数据
  } else {
   //请求失败,未得到响应数据
  }
 }
}; //补充说明:注册事件必须发生在send()以前
Copy after login
XMLHttpRequest对象的事件属性ontimeout -----仅限IE8+,不过最新的主流高版本浏览器也已经实现(不推荐使用)
xhr.timeout=1000;//一秒钟
xhr.ontimeout=functon(){  //处理代码  ......}
Copy after login

There is a problem that needs to be paid attention to in this usage method, that is, after the timeout, the onreadystatechange event will still be triggered after receiving the data. If the xhr.status attribute is accessed when processing the onreadychange event, an error will occur. So we need to do try{}catch processing when accessing this property. However, because this attribute is not compatible for the time being, we will not focus on it.

Event attributes onload onerror onloadstar onbort onprogress of the XMLHttpRequest object:

                               -----Non-IE browsers and IE 10 have been implemented

onload can be implemented in IE8 or above, Most events can be implemented based on readySate changes. The above events are just for convenience.

onload and onprogress These two events correspond to readyState=4 and readyState=3 respectively. The usage methods are as follows:

   xhr.onload= function (event) {
      //event只包含一个属性 event.target=xhr;使用方式只是在readyState=4时差不多..
    }
   xhr.onprogress=function(event){
     //event除了包含event.target=xhr之外,还包含三种属性
     //lengthComputale(进度信息是否可用),position(已接受字节数)和totalSize(总字节数).
     
   }
Copy after login

Additional: Some events can be based on readyState status is simulated. Only some browsers have made it easier.


3. One-way cross-domain technology ---CORS

Today we are talking about the client web page requesting data from a server that is not in the same domain. The client is receiving When the returned data is received, use the callback function to process the data. That is:

1. The client requests data from the out-of-domain server

2. The server sends data to the client after receiving the response.

3. The client executes the callback function based on the returned data.

我知道不同域下的iframe也可以进行通信,而且这也是一种跨域通信技术。但是,这种iframe页面之间的双向通信,我们在下一个专题里面讲解,今天主要讲的是单向通信。

3.1.CORS跨域请求的原理
在用xhr(XMLHttpRequest)对象或者xdr(XDomainRequest)对象,发送域外请求时,大概的实现原理如下图:

3.2.IE中CORS技术的实现
IE8引入了一个XDR类型,这个类型与XHR基本类似,但是其能实现安全可靠地跨域通信。

XHD的特点:

1.cookie不会随请求发送,也不会随响应返回。

2.只能设置请求头部中的Content-Type片段。

3.不能访问响应头部信息。

4.只是支持get和post请求。

XDR支持onload和onerror事件属性,且其使用方式和XHR基本一致,不过其open()只接收两个参数,默认是异步的。

var xdr = new XDomainRequest();
xdr.onload = function () {
 //处理xdr.responseText
}
xdr.onerror = function () {
};
xdr.open(&#39;get&#39;, &#39;绝对url&#39;);
xhr.send(null);
Copy after login

3.3.跨浏览器的CORS技术实现

在标准浏览器中XHR对象就已经可以自动实现跨域请求,但是XHR和XDR的不同之处:

1.XHR可以在设置 withCredentials =true时,浏览器会把cookie发送给服务器,服务器此时通过设置头部Access-Control-Allow-Credentials:true时来响应。如果,服务器不设置这个属性,则浏览器会触发onerror事件。

2.在回调函数中可以访问status和statusText属性,而且支持同步请求。

以下是实现跨域请求的代码:

function createCrosRequest(method, url) {
 var xhr = new XMLHttpRequest(); //IE7+
 if (&#39;withCredentials&#39; in xhr) { //IE8-IE9浏览器没有这个属性
  xhr.open(method, url, true);
 } else if (typeof XDomainRequest != &#39;undefined&#39;) {
  xhr = new XDomainRequest();  //IE
  xhr.open(method, url)
 }
 return xhr;
}
var request=CreateCrosRequest("get","url");
if(request){
 request.onload=function(){
 //处理request.responseText;
 }
 request.send(null);
}
Copy after login

4.单向跨域技术 ---JSONP技术

JSONP技术比较简单,其主要原理主要是利用script标签的特性。

script标签和image标签一样,它们都具有src属性,而且这个属性是可跨域的。

因为script标签返回的都是js代码,且该js代码会自动执行。所以,如果我们请求返回的数据也是类似一段js代码的形式,岂不是就可以实现在脚本加载完毕后自动执行。

如果我们的请求,返回的数据是 callback + '(' + json + ')'; 这种形式的数据, 那么在脚本加载完毕之后也就能自动执行callback()函数了.

4.1.客户端写法

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
    <button id="button">请求数据</button>
</body>
<script>
  window.onload=function(){
    var button=document.getElementById("ibutton");
    function callback(data){
      //处理data
    }
    button.onclick=function(){
      var script=document.createElement("script");
      script="http://www.sasd.com/json/?callbak=callback"; 
      document.body.insertBefore(script,document.body.firstChild);//加载脚本
      
    }
    
  }
</script>
</html>
Copy after login

   1.客户端将回调函数名写入

Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template