Home Web Front-end JS Tutorial Detailed explanation of AJAX mechanism and cross-domain communication

Detailed explanation of AJAX mechanism and cross-domain communication

May 25, 2018 am 11:42 AM
ajax communication

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.客户端将回调函数名写入

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

New generation of optical fiber broadband technology - 50G PON New generation of optical fiber broadband technology - 50G PON Apr 20, 2024 pm 09:22 PM

In the previous article (link), Xiao Zaojun introduced the development history of broadband technology from ISDN, xDSL to 10GPON. Today, let’s talk about the upcoming new generation of optical fiber broadband technology-50GPON. █F5G and F5G-A Before introducing 50GPON, let’s talk about F5G and F5G-A. In February 2020, ETSI (European Telecommunications Standards Institute) promoted a fixed communication network technology system based on 10GPON+FTTR, Wi-Fi6, 200G optical transmission/aggregation, OXC and other technologies, and named it F5G. That is, the fifth generation fixed network communication technology (The5thgenerationFixednetworks). F5G is a fixed network

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

The development history of wireless mice The development history of wireless mice Jun 12, 2024 pm 08:52 PM

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

A brief history of broadband Internet technology A brief history of broadband Internet technology Apr 16, 2024 am 09:00 AM

In today's digital age, broadband has become a necessity for each of us and every family. Without it, we would be restless and restless. So, do you know the technical principles behind broadband? From the earliest 56k "cat" dial-up to the current Gigabit cities and Gigabit homes, what kind of changes has our broadband technology experienced? In today’s article, let’s take a closer look at the “Broadband Story”. Have you seen this interface between █xDSL and ISDN? I believe that many friends born in the 70s and 80s must have seen it and are very familiar with it. That's right, this was the interface for "dial-up" when we first came into contact with the Internet. That was more than 20 years ago, when Xiao Zaojun was still in college. In order to surf the Internet, I

Methods and techniques for implementing Socket communication in PHP Methods and techniques for implementing Socket communication in PHP Mar 07, 2024 pm 02:06 PM

PHP is a commonly used development language that can be used to develop various web applications. In addition to common HTTP requests and responses, PHP also supports network communication through Sockets to achieve more flexible and efficient data interaction. This article will introduce the methods and techniques of how to implement Socket communication in PHP, and attach specific code examples. What is Socket Communication Socket is a method of communication in a network that can transfer data between different computers. by S

See all articles