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

jquery下利用jsonp跨域访问实现方法_jquery

WBOY
Release: 2016-05-16 18:22:08
Original
1022 people have browsed it
复制代码 代码如下:

$.ajax({
async:false,
url: '', // 跨域URL
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback', //默认callback
data: mydata, //请求数据
timeout: 5000,
beforeSend: function(){ //jsonp 方式此方法不被触发。原因可能是dataType如果指定为jsonp的话,就已经不是ajax事件了
},
success: function (json) { //客户端jquery预先定义好的callback函数,成功获取跨域服务器上的json数据后,会动态执行这个callback函数
if(json.actionErrors.length!=0){
alert(json.actionErrors);
}

},
complete: function(XMLHttpRequest, textStatus){

},
error: function(xhr){
//jsonp 方式此方法不被触发
//请求出错处理
alert("请求出错(请检查相关度网络状况.)");
}
});



复制代码 代码如下:

$.getJSON(url+"?callback=?",
function(json){

});

这种方式其实是上例$.ajax({..}) 的一种高级封装。

在服务端通过获得callback参数(如:jsonp*****)得到jQuery端随后要回调的
然后返回类似:"jsonp*****("+要返回的json数组+")";
jquery就会通过回调方法动态加载调用这个:jsonp*****(json数组);
这样就达到了跨域数据交换的目的.

JSONP是一种脚本注入(Script Injection)行为,所以也有一定的安全隐患。

注意:jquey是不支持post方式跨域的。
参考:http://www.ibm.com/developerworks/cn/web/wa-aj-jsonp1/
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!