最近公司开发的项目中很多地方需要跨域ajax请求,比如几个子域名下
http://a.****.com/index123.aspx,
http://b.****.com/index2.aspx
都要请求用户json信息,然后再对数据进行处理,起初我和同事们试了很多种方法,使用$.ajax() 无论是get或post方法都会引起uri deny的错误。一番GG之后发现了解决方法,也了解其中的原因。
jquery从1.2开始,.getJSON就支持跨域操作了。使用jquery.getJSON()方法可以解决跨域问题。实例如下
前台
<script type="text/javascript" src="/script/jquery.js"></script>
HTML中JS代码
function gettst2() {
$.getJSON("http://ucenter.xxxx.com.cn/ajax/test.aspx?callback=?", { id: "123456", site: "01" },
function(data) {
alert(data.htmls);
document.getElementById("shows").innerHTML = data.htmls;
});
}
gettst2();
ASPX.cs文件中处理为
string jsoncall = Request.QueryString("callback");
Response.Write(jsoncall + "({htmls:测试001})");
使用jquery的jsonp来实现跨域访问,例子如下:
Java代码
- <script type="text/javascript">
- $(function(){
- $.ajax({
- type: "get",
- async: false,
- url: "http://abc.com:8080/AjaxCrossDomain/jsonp/data.jsp",
- dataType: "jsonp",
- jsonp: "callback",
- jsonpCallback:"flightHandler",
- success: function(json){
- alert('您查询到航班信息:票价: ' + json.price + ' 元,余票: ' + json.tickets + ' 张。');
- },
- error: function(){
- alert('fail');
- }
- });
- });
- </script>