码迷,mamicode.com
首页 > Web开发 > 详细

ashx+jsonp+document.referrer

时间:2016-09-12 17:10:11      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

技术分享--

一年前学的JSONP 跨域,一年后的今天相关知识点基本忘光。花了一天时间重新学习,再次感谢各位前辈的帖子,特此记录如下。

--html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ashx+jsonp+UrlReferrer</title>
<script type="text/javascript" src="Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(
    function () {
        $("#btn").click(function () {

            var url = "http://192.168.1.48:6060/Ashx/test_json.ashx";
            $.ajax({
                type: "get",
                async: false,
                url: url,
                dataType: "jsonp", //数据类型为jsonp  
                jsonp: "jsonp", //服务端用于接收callback调用的function名的参数  
                jsonpCallback: "callback",//跟ashx的函数名一致
                success: function (result) {
                    alert(result.id+‘-‘+ result.name + ‘-‘+ result.host);
                },
                error: function (fail) {
                    alert(fail);
                }

            })

        });
    })
     </script>
</head>

<body>
<div>
<a href="http://192.168.1.48:6060/Ashx/test.ashx" >点击跳转ashx</a>
<button id="btn" >json</button>
</div>
</body>
</html>

 --ashx

 public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            if (context.Request == null || context.Request.UrlReferrer == null)
            {
                context.Response.Write("error: not get referrer");
                return;
            }
            else
            {
                if (context.Request.UrlReferrer.Host.IndexOf("192.168.1.252") > -1)
                {
                    context.Response.Write("callback({\"id\": 123,\"name\":\"jason\",\"host\":\"" + context.Request.UrlReferrer.Host + "\"})");    // 返回字符串前加 callback包裹成JS方法方可解析
                }
            }
        }

 重要知识点:

1、ashx里面,response输出的json字符串必须包裹在callback()里面,必须和html的jQuery函数jsonpCallback: "callback" 一致。(非常重要,否则报错)。

因为jQuery成功解析的字符串要求如下:

callback({"id": 123,"name":"jason","host":"192.168.1.252"})

2、json的列名必须用双引号包裹,如"name",在C#里加\转义字符,如\"name\"。

3、document.referrer 是只读属性,可防止盗链,伪链,一般使用<a href="">跳转</a>  才不为null,直接使用js跳转window.open()无效,服务器后台界面可使用Response.Redirect("ashx_jsonp")。

4、使用jQuery的click方法也可以获取document.referrer。

 

ashx+jsonp+document.referrer

标签:

原文地址:http://www.cnblogs.com/cyg17173/p/5865364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!