jsonp跨域解决方案
发布时间:2020-12-16 19:02:32 所属栏目:百科 来源:网络整理
导读:1.jquery 原生ajax调用,缺点是没有捕获调用的异常信息 $.ajax({ type : "get", async:false, url : "http://localhost:11180/xzinterface/jsonpService?action=qryDepartment", dataType : "jsonp",//数据类型为jsonp jsonp: " jsonpCallback ",//服务端用
1.jquery 原生ajax调用,缺点是没有捕获调用的异常信息
$.ajax({
type : "get",
async:false,
url : "http://localhost:11180/xzinterface/jsonpService?action=qryDepartment",
dataType : "jsonp",//数据类型为jsonp
jsonp: "jsonpCallback",//服务端用于接收callback调用的function名的参数
success : function(data){
alert(data);
},
error:function(){
alert('fail');
}
});
2.使用插件jquery.jsonp.js,可以解决捕获调用的异常信息
$.jsonp({
url:
'
http://localhost:11180/xzinterface/jsonpService?action=qryDepartment',
dataType:
"jsonp"
,
callbackParameter:
"jsonpCallback"
,
async:
false
,
timeout:5000,
success:
function
(data){
alert(data);
},
error:
function
(XMLHttpRequest,textStatus,errorThrown) {
//alert("wrong!!");
alert(
"ERREUR: "
+ textStatus);
alert(
"ERREUR: "
+ errorThrown);
},
complete:
function
(XMLHttpRequest,textStatus) {
// alert("over")
this
;
// 调用本次AJAX请求时传递的options参数
}
});
以上两个方法调用后的url为:
http://localhost:11180/xzinterface/jsonpService?action=qryDepartment
?
jsonpCallback
='xxxxxx'&_=yyyyy
其中xxxxxxx为自动生成的回调函数名
3.后台代码很简单:
String
jsonpCallback
=
request
.getParameter(
"jsonpCallback"
);
//客户端请求参数,获取回调函数名
result
=
jsonpCallback
+
"("
+
service
.qryDepartment()+
")"
;//
service
.qryDepartment()为具体的返回数据
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |