Detailed explanation of AJAX mechanism and cross-domain 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; }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对象'); } }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 请求。
XMLHttpRequest There are 5 attributes of the object:
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 documentstatus 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
xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status <== 300 || xhr.status == 304) { alert(xhr.responseText); //处理接收的数据 } else { //请求失败,未得到响应数据 } } }; //补充说明:注册事件必须发生在send()以前
XMLHttpRequest对象的事件属性ontimeout -----仅限IE8+,不过最新的主流高版本浏览器也已经实现(不推荐使用) xhr.timeout=1000;//一秒钟 xhr.ontimeout=functon(){ //处理代码 ......}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(总字节数). }
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:
我知道不同域下的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('get', '绝对url'); xhr.send(null);
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 ('withCredentials' in xhr) { //IE8-IE9浏览器没有这个属性 xhr.open(method, url, true); } else if (typeof XDomainRequest != 'undefined') { 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); }
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>
1.客户端将回调函数名写入<script>脚本的url参数中。</script>
2.script加载的时候会发送跨域请求。
4.2.服务器端
1.通过url得到函数名,命名为callback
2.将请求的数据作为函数的参数格式转化json格式,命名为。
3.将返回结果拼接为 callback+"("+json+")"; --------返回的就是填充式的数据,这段数据在脚本中会自动执行。
4.返回数据.
4.3.JSONP技术的缺点
1.因为是通过url传参数,所以请求只能是get类型的。
2.<script>目前只有onload属性事件,onerror还没有统一化,如果加载脚本出错,客户端很难得到反馈。</script>
3.所请求数据的站点必须是可信任的,如果返回的数据段中注入的有恶意的代码,危害较大,且难以发现。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
JQuery ajax 返回json时出现中文乱码该如何解决
The above is the detailed content of Detailed explanation of AJAX mechanism and cross-domain communication. For more information, please follow other related articles on the PHP Chinese website!

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

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'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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment