* 支持跨域Ajax调用的 JavaScript API,
* 使用时在服务器响应端添加响应头:Response.AddHeader("Access-Control-Allow-Origin","*")
* 版本支持:IE8以上,chrome,firefox
* @author ketqi
*/
var CrossDomain = {
/**
* <pre>
* opts{
* url:null,//请求的地址
* param:null,//需传入的参数
* type:"get",//请求方法
* dataType = "json",//返回的数据格式,json和text
* success:callback(re),//成功后执行的回调函数
* error:callback(),//失败后的回调函数
* timeout:callback(),//超时后的回调函数
* }
* </pre>
*/
invoke : function(opts) {
// browser IE8 realse support XDomainRequest
if (navigator.appName == "Microsoft Internet Explorer") {
var version = navigator.appVersion.split(";")[1].replace(/[ ]/g, "");
if (version == "MSIE6.0" || version == "MSIE7.0") {
alert("no support IE6,IE7");
return;
} else {
if (window.XDomainRequest) {
var xdr = new XDomainRequest();
if (xdr) {
//handle error callback function
if (opts.error && typeof opts.error == "function") {
xdr.onerror = function(){
opts.error();
};
}
//handle timeout callback function
if (opts.timeout && typeof opts.timeout == "function") {
xdr.ontimeout = function(){
opts.timeout();
};
}
//handle success callback function
if (opts.success && typeof opts.success == "function") {
xdr.onload = function(){
if(opts.dataType){//handle json formart data
if(opts.dataType.toLowerCase() == "json"){
opts.success(JSON.parse(xdr.responseText));
}
}else{
opts.success(xdr.responseText);
}
};
}
//wrap param to send
var data = "";
$.each(opts.param,function(k,v){
data += k + "=" + v + "&";
});
data = data.substring(0,data.length - 1);
xdr.open(opts.type, opts.url);
xdr.send(data);
} else {
alert('Failed to create XDomainRequest');
}
}
}
} else {// browser chrome,firefox
//use jquery ajax handle other request
$.ajax({
url : opts.url,
type : opts.type,
dataType : opts.dataType,
data : opts.param,
success : opts.success,
error : opts.error,
timeout : opts.timeout
});
}
}
};
<html>
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="./crossDomain.js"></script>
</head>
<body>
<!-- Response.AddHeader("Access-Control-Allow-Origin","*") -->
<script type="text/javascript">
$(function() {
$("#crossDomain").click(function(){
CrossDomain.invoke({
url:"url",
type:"get",
param:{idx:1},
dataType:"text",
success:function(re){
alert(re);
}
});
});
});
</script>
<a href="javascript:void()" id="crossDomain">跨域</a>
<div id="results"></div>
</body>
</html>
参考资料: