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

Basic process of ajax cross-domain

爱喝马黛茶的安东尼
Release: 2019-06-20 14:05:42
Original
3392 people have browsed it

1. AJAX

AJAX (Asynchronous JavaScript and XML) means using JavaScript to perform asynchronous network requests.
Cross-domain can be achieved mainly by setting up a proxy server, JSONP and CORS.
Writing a complete AJAX code in JavaScript is not complicated, but it needs to be noted: AJAX requests are executed asynchronously, that is, they need to be Get the response through the callback function.

Related recommendations: "python Video"

Basic process of ajax cross-domain

##The process of creating ajax is generally as follows:

Create an XMLHttpRequest object, that is, create an asynchronous call object; determine the XHR object attributes; create a new HTTP request, and specify the method, URL and verification information of the HTTP request; set a function to respond to changes in the status of the HTTP request; send HTTP request; obtain the data returned by the asynchronous call; use JavaScript and DOM to implement partial refresh.

Code.

var xmlhttp;function createXMLHttpRequest () {
    xmlhttp = null;    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
    }    // 异步调用服务器段数据
    if (xmlhttp != null) {        // 创建http请求
        xmlhttp.open('GET/POST', url, true);        // 设置http请求状态变化的函数
        xmlhttp.onreadystatechange = httpStateChange;        // 发送请求
        xmlhttp.send(null);
    } else {        console.log('不支持XHR');
    }
} 
// 响应HTTP请求状态变化的函数function httpStateChange () { //判断异步调用是否完成
    if (xmlhttp.readyState == 4) {//readyState==4表示后台处理完成了
        if (xmlhttp.status >= 200 && xmlhttp.status < 300 || xmlhttp.status == 304){        //判断异步调用是否成功,如果成功开始局部更新数据
            //code...
        } else{            console.log("出错状态码:" + xmlhttp.status + "出错信息:" + xmlhttp.statusText);
        }
    }
}
Copy after login

For lower versions of IE, you need to change to an ActiveXObject object. If you want to mix standard writing and IE writing, you can write like this.

var request;if (window.XMLHttpRequest) {
   request = new XMLHttpRequest();
} else {
  request = new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);
}
Copy after login

Determine whether the browser supports standard XMLHttpRequest by detecting whether the window object has an XMLHttpRequest attribute. Note, do not use the browser's navigator.userAgent to detect whether the browser supports a certain JavaScript feature. First, because the string itself can be forged, and second, it will be very complicated to judge the JavaScript feature through the IE version.

After creating the XMLHttpRequest object, you must first set the callback function of onreadystatechange

. In the callback function, usually we only need to judge whether the request is completed through readyState === 4. If it is completed, then judge whether it is a successful response based on status.

The open() method of the XMLHttpRequest object has 3 parameters. The first parameter specifies whether it is GET or POST, the second parameter specifies the URL address, and the third parameter specifies whether to use asynchronous. The default is true, so No need to write. Note, never specify the third parameter as false, otherwise the browser will stop responding until the AJAX request is completed. If this request takes 10 seconds, then within 10 seconds you will find that the browser is in a "suspended death" state.

Finally call the send() method to actually send the request. GET requests do not require parameters, and POST requests require the body part to be passed in as a string or FormData object.

2. Cross-domain security restrictions

Because of the browser's "same origin policy", if the protocol, domain name, and port number are different, access will not be possible. AJAX itself cannot cross domains. AJAX directly requests ordinary files, which has the problem of cross-domain access without permission. As long as it is a cross-domain request, it is not allowed; however, it can cross domains with the backend.

Because the same-origin policy restricts the browser but does not restrict the server, the server can cross domains.

Is it because JavaScript cannot request URLs from external domains (that is, other websites)? There are still methods, probably the following.

2.1 CORS

CORS (Cross-Origin Resource Sharing, cross-origin resource sharing) is a draft of W3C, which defines how to browse when cross-domain resources must be accessed. How should the server communicate with the server.

The basic idea behind CORS is to use custom HTTP headers to allow the browser to communicate with the server to determine whether the request or response should succeed or fail.

For example, a simple request sent using GET or POST has no custom header, and the main content is text/plain. When sending this request, you need to attach an additional Origin header to it, which contains the source information of the requested page (protocol, domain name, and port) so that the server can decide whether to respond based on this header information. Below is an example of the Origin header.

Origin: http://www.nczonline.net
Copy after login

If the server thinks that the request is acceptable, it will send back the same source information in the Access-Control-Allow-Origin header (if it is a public resource, it can send back '*'). For example:

Access-Control-Allow-Origin: http://www.nczonline.net
Copy after login

If there is no such header, or there is this header but the source information does not match, the browser will reject the request. Normally, the browser handles the request. Note that neither the request nor the response contains cookie information.

Currently, all browsers support this function, and IE browser cannot be lower than IE10. The entire CORS communication process is automatically completed by the browser and does not require user participation. For developers, there is no difference between CORS communication and AJAX communication from the same source, and the code is exactly the same. Once the browser discovers that the AJAX request is cross-origin, it will automatically add some additional header information, and sometimes an additional request will be made, but the user will not feel it.

Therefore, the key to achieving CORS communication is the server. As long as the server implements the CORS interface, cross-origin communication is possible.

Usual ajax requests may look like this:

<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/damonare",true);
    xhr.send();</script>
Copy after login

The damonare part above is a relative path. If we want to use CORS, the relevant Ajax code may look like this:

<script type="text/javascript">
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "http://segmentfault.com/u/trigkit4/",true);
    xhr.send();</script>
Copy after login

The difference between the code and the previous one is that the relative path is replaced by the absolute path of other domains, which is the interface address you want to access across domains.

服务器端对于CORS的支持,主要就是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。

2.2 图像Ping

我们知道,一个网页可以从任何网页中加载图像,不用担心跨域不跨域。这也是在线广告跟踪浏览量的主要方式。我们也可以动态的创建图像,使用它们的onload和onerror事件处理成西来确定是否接收到了响应。

动态创建图像经常用于图像Ping。
图像Ping是与服务器进行简单、单向的跨域通信的一种方式。请求的数据是通过查询字符串形式发送的,而响应可以是任意内容,但通常是像素图或204响应。通过图像Ping,浏览器得不到任何具体的数据,但通过侦听load和error事件,它能知道响应是什么时候收到的。

来看下面的例子。

var img = new Image();
img.onload = img.onerror = function () {    console.log(&#39;Done&#39;);
};
img.src = &#39;http://www.example.com/test?name=Nico&#39;;
Copy after login

这里创建了一个Image的实例,然后将onload和onerror事件处理程序指定为同一个函数。这样无论是什么响应,只要请求完成,就能得到通知。请求从设置src属性那一刻开始,而这个例子在请求中发送了一个name参数。

图像Ping最常用于跟踪用户点击页面或动态广告曝光次数。
图像Ping有两个主要的缺点:

只能发送GET请求。无法访问服务器的响应文本。

因此,图像Ping只能用于浏览器与服务器间的单向通信。

2.3 JSONP

JSONP是JSON with padding(填充式JSON或参数式JSON)的简写,是应用JSON的一种新方法。JSONP与JSON看起来差不多,只不过是被包含在函数调用中的JSON,如下。

callback({&#39;name&#39;: &#39;Azure&#39;});
Copy after login

JSONP由两部分组成:回调函数和数据。回调函数是当响应到来时应该在页面中调用的函数。回调函数的名字一般是在请求中指定的,而数据就是传入回调参数中JSON数据。下面是一个典型的JSONP请求。

http://freegeoip.net/json/?callback=handleResponse
Copy after login

这个URL是在请求一个JSONP地理定位服务。通过查询字符串来指定JSONP服务的回调参数是很常见的,就像上面的URL所示,这里指定的回调函数的名字叫handleResponse()。

JSONP是通过动态

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