search
HomeWeb Front-endJS TutorialBasic process of ajax cross-domain

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);
        }
    }
}

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;);
}

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

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

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>

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>

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;;

这里创建了一个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;});

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

http://freegeoip.net/json/?callback=handleResponse

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

JSONP是通过动态<script>元素来使用的,使用时可以为src属性指定一个跨域URL。<br/>这里的<scriot>元素与<img alt="Basic process of ajax cross-domain" >元素类似,都有能力不受限制的从其他域加载资源。因为JSONP是有效的JS代码,所以在请求完成后,即在JSONP响应加载到页面中以后,就会立即执行。来看一个例子。</script>

function handleResponse (response) {    
console.log(&#39;u r at IP address &#39; + response.ip + &#39;, which is in &#39; + response.city + &#39;, &#39; + response.region_name);
} 
var script = document.createElement(&#39;script&#39;);
script.src = &#39;http://freegeoip.net/json/?callback=handleResponse&#39;;
document.body.insertBefore(script, document.body.firstChild);

这个例子通过查询地理定位服务来显示IP地址和地理位置信息。

JSONP之所以在开发人员中极为流行,主要原因是它非常简单易用。与图像Ping相比,它的优点在于能够直接访问响应文本,支持在浏览器与服务器之间双向通信。不过,JSONP也有两点不足。

首先,安全性问题。JSONP是从其他域中加载代码执行。如果其他域不安全,很可能会在响应中夹带一些恶意代码,而此时除了完全放弃JSONP调用之外,没有办法追究。因此在使用不是自己运维的Web服务时,一定得保证它安全可靠。
其次,要确定JSONP请求是否失败并不容易。

CORS和JSONP对比

JSONP只能实现GET请求,而CORS支持所有类型的HTTP请求。使用CORS,开发者可以使用普通的XMLHttpRequest发起请求和获得数据,比起JSONP有更好的错误处理。SONP主要被老的浏览器支持,它们往往不支持CORS,而绝大多数现代浏览器都已经支持了CORS。

The above is the detailed content of Basic process of ajax cross-domain. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools