search
HomeWeb Front-endJS TutorialAbout the way ajax handles cross-domain in jquery

About the way ajax handles cross-domain in jquery

Jun 30, 2018 am 10:27 AM
ajaxjqueryCross domain

这篇文章主要介绍了jquery中ajax处理跨域的三大方式,感兴趣的小伙伴们可以参考一下

由于JS同源策略的影响,因此js只能访问同域名下的文档。因此要实现跨域,一般有以下几个方法:

一、处理跨域的方式:

1.代理

2.XHR2

HTML5中提供的XMLHTTPREQUEST Level2(及XHR2)已经实现了跨域访问。但ie10以下不支持

只需要在服务端填上响应头:

 header("Access-Control-Allow-Origin:*");
 /*星号表示所有的域都可以接受,*/
 header("Access-Control-Allow-Methods:GET,POST");

3.jsonP

原理:

 ajax本身是不可以跨域的,
通过产生一个script标签来实现跨域。因为script标签的src属性是没有跨域的限制的。

其实设置了dataType: 'jsonp'后,$.ajax方法就和ajax XmlHttpRequest没什么关系了,取而代之的则是JSONP协议。JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问。

 ajax的跨域写法:

(其余写法和不跨域的一样):

比如 

 /*当前网址是localhost:3000*/
 js代码
 
 $.ajax({
 type:"get",
 url:"http://localhost:3000/showAll",/*url写异域的请求地址*/
 dataType:"jsonp",/*加上datatype*/
 jsonpCallback:"cb",/*设置一个回调函数,名字随便取,和下面的函数里的名字相同就行*/
 success:function(){
 。。。
 }
 });

 /*而在异域服务器上,*/
 app.js
 app.get('/showAll',students.showAll);/*这和不跨域的写法相同*/
 
 
 /*在异域服务器的showAll函数里,*/

 var db = require("./database");

 exports.showAll = function(req,res){

 /**设置响应头允许ajax跨域访问**/
 res.setHeader("Access-Control-Allow-Origin","*");
 /*星号表示所有的异域请求都可以接受,*/
 res.setHeader("Access-Control-Allow-Methods","GET,POST");

 var con = db.getCon();
 con.query("select * from t_students",function(error,rows){
 if(error){
 console.log("数据库出错:"+error);
 }else{
 /*注意这里,返回的就是jsonP的回调函数名+数据了*/
 res.send("cb("+JSON.stringify(r)+")");
 }
 });
 }

二、解决ajax跨域访问、 JQuery 的跨域方法

 JS的跨域问题,我想很多程序员的脑海里面还认为JS是不能跨域的,其实这是一个错误的观点;有很多人在网上找其解决方法,教其用IFRAME去解决的文章很多,真有那么复杂吗?其实很简单的,如果你用JQUERY,一个GETJSON方法就搞定了,而且是一行代码搞定。

下面开始贴出方法。

//跨域(可跨所有域名)
$.getJSON("http://user.hnce.com.cn/getregion.aspx?id=0&jsoncallback=?",function(json){ 
//要求远程请求页面的数据格式为: ?(json_data) //例如: //?([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}]) alert(json[0]._name); 
}); 

$.getJSON("http://user.hnce.com.cn/getregion.aspx?id=0&jsoncallback=?",function(json){ 
//要求远程请求页面的数据格式为: ?(json_data) //例如: //?([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}]) alert(json[0]._name); 
});

 注意,getregion.aspx中,在输出JSON数据时,一定要用Request.QueryString["jsoncallback"],将获取的内容放到返回JSON数据的前面,假设实际获取的值为42342348,那么返回的值就是 42342348([{"_name":"湖南省","_regionId":134},{"_name":"北京市","_regionId":143}])

因为getJSON跨域的原理是把?随机变一个方法名,然后返回执行的,实现跨域响应的目的。

下面一个是跨域执行的真实例子:

<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script> 
<script type="text/javascript"> 
//跨域(可跨所有域名) 
$.getJSON("http://e.hnce.com.cn/tools/ajax.aspx?jsoncallback=?", { id: 0, action: &#39;jobcategoryjson&#39; }, function(json) { alert(json[0].pid); alert(json[0].items[0]._name); });  
 </script>

<script src="http://common.cnblogs.com/script/jquery.js" type="text/javascript"></script> 
<script type="text/javascript"> 
//跨域(可跨所有域名) 
$.getJSON("http://e.hnce.com.cn/tools/ajax.aspx?jsoncallback=?", { id: 0, action: &#39;jobcategoryjson&#39; }, function(json) { alert(json[0].pid); alert(json[0].items[0]._name); });  
 </script>

jQuery跨域原理:

浏览器会进行同源检查,这导致了跨域问题,然而这个跨域检查还有一个例外那就是HTML的<script>标记;我们经常使用<Script>的src属性,脚本静态资源放在独立域名下或者来自其它站点的时候这里是一个url;这个url响应的结果可以有很多种,比如JSON,返回的Json值成为<Script>标签的src属性值.这种属性值变化并不会引起页面的影响.按照惯例,浏览器在URL的查询字符串中提供一个参数,这个参数将作为结果的前缀一起返回到浏览器;</script>

看下面的例子:

<script type="text/javascript" src="http://domain2.com/getjson?jsonp=parseResponse"> </script> 
响应值:parseResponse({"Name": "Cheeso", "Rank": 7}) 
<script type="text/javascript" src="http://domain2.com/getjson?jsonp=parseResponse"> </script> 
响应值:parseResponse({"Name": "Cheeso", "Rank": 7})

这种方式被称作JsonP;(如果链接已经失效请点击这里:JSONP);即:JSON with padding 上面提到的前缀就是所谓的“padding”。那么jQuery里面是怎么实现的呢?

貌似并没有<script>标记的出现!?OKay,翻看源码来看:</script>

页面调用的是getJSON:

getJSON: function( url, data, callback ) {
 return jQuery.get(url, data, callback, "json");
 },

 继续跟进

 get: function( url, data, callback, type ) {
 // shift arguments if data argument was omited
 if ( jQuery.isFunction( data ) ) {
  type = type || callback;
  callback = data;
  data = null;
 }
 
 return jQuery.ajax({
  type: "GET",
  url: url,
  data: data,
  success: callback,
  dataType: type
 });

跟进jQuery.ajax,下面是ajax方法的代码片段:

 // Build temporary JSONP function
 if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
 jsonp = s.jsonpCallback || ("jsonp" + jsc++);
 
 // Replace the =? sequence both in the query string and the data
 if ( s.data ) {
 s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
 }
 
 s.url = s.url.replace(jsre, "=" + jsonp + "$1");
 
 // We need to make sure
 // that a JSONP style response is executed properly
 s.dataType = "script";
 
 // Handle JSONP-style loading
 window[ jsonp ] = window[ jsonp ] || function( tmp ) {
 data = tmp;
 success();
 complete();
 // Garbage collect
 window[ jsonp ] = undefined;
 
 try {
  delete window[ jsonp ];
 } catch(e) {}
 
 if ( head ) {
  head.removeChild( script );
 }
 };
 }
 
 if ( s.dataType === "script" && s.cache === null ) {
 s.cache = false;
 }
 
 if ( s.cache === false && type === "GET" ) {
 var ts = now();
 
 // try replacing _= if it is there
 var ret = s.url.replace(rts, "$1_=" + ts + "$2");
 
 // if nothing was replaced, add timestamp to the end
 s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
 }

 // If data is available, append data to url for get requests
 if ( s.data && type === "GET" ) {
 s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
 }
 
 // Watch for a new set of requests
 if ( s.global && ! jQuery.active++ ) {
 jQuery.event.trigger( "ajaxStart" );
 }
 
 // Matches an absolute URL, and saves the domain
 var parts = rurl.exec( s.url ),
 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
 
 // If we&#39;re requesting a remote document
 // and trying to load JSON or Script with a GET
 if ( s.dataType === "script" && type === "GET" && remote ) {
 var head = document.getElementsByTagName("head")[0] || document.documentElement;
 var script = document.createElement("script");
 script.src = s.url;
 if ( s.scriptCharset ) {
 script.charset = s.scriptCharset;
 }
 
 // Handle Script loading
 if ( !jsonp ) {
 var done = false;
 
 // Attach handlers for all browsers
 script.onload = script.onreadystatechange = function() {
  if ( !done && (!this.readyState ||
  this.readyState === "loaded" || this.readyState === "complete") ) {
  done = true;
  success();
  complete();
 
  // Handle memory leak in IE
  script.onload = script.onreadystatechange = null;
  if ( head && script.parentNode ) {
  head.removeChild( script );
  }
  }
 };
 }
 
 // Use insertBefore instead of appendChild to circumvent an IE6 bug.
 // This arises when a base node is used (#2709 and #4378).
 head.insertBefore( script, head.firstChild );
 
 // We handle everything using the script element injection
 return undefined;
 }

上面的代码第1行到第10行:判断是JSON类型调用,为本次调用创建临时的JsonP方法,并且添加了一个随机数字,这个数字源于用日期值;

 关注第14行,这一行相当关键,注定了我们的结果最终是<script> ;然后是构造Script片段,第95行在Head中添加该片段,修成正果;</script>

 不仅仅是jQuery,很多js框架都是用了同样的跨域方案,这就是getJSON跨域的原理。

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

jquery$.ajax()方法

jQuery实现获取动态添加的标签对象

The above is the detailed content of About the way ajax handles cross-domain in jquery. 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
Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function