首页 > Web开发 > 详细

jQuery Ajax跨域问题简易解决方案

时间:2017-02-15 16:18:35      阅读:202      评论:0      收藏:0      [点我收藏+]

场景:由于业务需求,需要在一个页面显示另外一个页面,并且右键查看源代码看不到一条链接。

实现方式:使用iframe来显示这个首页,至于首页的地址则使用jQuery Ajax来获取。html代码如下:

<html>
<head>
<title></title>
<script src=""https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.2.min.js"" type=""text/javascript""></script>
<style type=""text/css"">
    body { overflow-x:hidden; overflow-y:hidden;} 
    html, body, iframe { width:100%; height:100%; margin:0px; padding:0px;}
</style>
<script type=""text/javascript"">
    $(function(){
          $.ajax({
            url: """ + iisUrl + @"/Ajax/SnapsHijackService.ashx"",
            type: POST,
            dataType: json,
            data:{ releaseId: " + releaseId + @" },
            success: function(data) {
                var url = $.trim(decodeURIComponent(data.url));
                $(""#iframe"").attr(""src"",url);
            },
            error:function(data){
                alert(data);
                console.log(data.url);
            }
         });
    });
</script>
</head>
<body>
<iframe id=""iframe"" frameborder=‘no‘></iframe>
</body>
</html>

       SnapsHijackService.ashx代码如下:

string sql = "select user_site_url from t_synth_release_site where id = " + releaseId;
string url = string.Empty;
System.Data.DataTable dtUrl = NetWin.SnapsHijack.Common.Helper.MysqlHelper.Select(sql);
if (dtUrl == null || dtUrl.Rows.Count == 0)
{
    log.Write("读取广告计划:" + releaseId + "的官网代码失败。sql:" + sql);
    return;
}

url = dtUrl.Rows[0]["user_site_url"].ToString().ToLower();
if (!url.StartsWith("http"))
{
    url = "http://" + url;
    log.Write("广告计划网址:" + url);
}

string result = "{\"url\":\"" + UrlEncode(url) + "\"}";

context.Response.Write(result);
context.Response.End();

出现的问题:由于业务需求,需要在别的站点通过反向代理的方式来请求这个一般处理程序,如此就会因为js的同源策略导致获取url失败。

解决方案一:只需要在一般处理程序那里添加一句话即可解决问题。此法在IE9中无效。在FireFox、Chrome中可行。

...
string result = "{\"url\":\"" + UrlEncode(url) + "\"}";

context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.Write(result);
context.Response.End();

解决方案二:修改ajax的返回类型。具体看代码:

<html>
<head>
<title></title>
<script src=""https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.7.2.min.js"" type=""text/javascript""></script>
<style type=""text/css"">
    body { overflow-x:hidden; overflow-y:hidden;} 
    html, body, iframe { width:100%; height:100%; margin:0px; padding:0px;}
</style>
<script type=""text/javascript"">
    $(function(){
          $.ajax({
            url: """ + iisUrl + @"/Ajax/SnapsHijackService.ashx"",
            type: get,
           dataType: ""jsonp"",
           jsonp: ""callbackparam"",
           jsonpCallback:""jsonpCallback1"",
            data:{ releaseId: " + releaseId + @" },
            success: function(data) {
                var url = $.trim(decodeURIComponent(data[0].url));
                $(""#iframe"").attr(""src"",url);
            },
            error:function(data){
                alert(""error"");
            }
         });
    });
</script>
</head>
<body>
<iframe id=""iframe"" frameborder=‘no‘></iframe>
</body>
</html>

     一般处理程序:

string sql = "select user_site_url from t_synth_release_site where id = " + releaseId;
string url = string.Empty;
System.Data.DataTable dtUrl = Common.Helper.MysqlHelper.Select(sql);
if (dtUrl == null || dtUrl.Rows.Count == 0)
{
    log.Write("读取广告计划:" + releaseId + "的官网代码失败。sql:" + sql);
    return;
}

url = dtUrl.Rows[0]["user_site_url"].ToString().ToLower();
if (!url.StartsWith("http"))
{
    url = "http://" + url;
    log.Write("广告计划网址:" + url);
}

string callbackFunName = context.Request["callbackparam"];
string result = callbackFunName + "([{\"url\":\"" + UrlEncode(url) + "\"}])";
//context.Response.AddHeader("Access-Control-Allow-Origin", "*");
context.Response.Write(result);
context.Response.End();

      如此,IE、FireFox、Chrome就都可以了。ajax请求的链接为:http://wuzhoumh.paiming.net/Ajax/SnapsHijackService.ashx?callbackparam=jsonpCallback1&releaseId=988&_=1487146317414

参考文档:http://www.cnblogs.com/mahatmasmile/archive/2013/03/29/2989505.html

jQuery Ajax跨域问题简易解决方案

原文:http://www.cnblogs.com/wangwust/p/6401760.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!