转载:http://www.cnblogs.com/cyg17173/p/5865364.html
ashx+jsonp+document.referrer
--
一年前学的JSONP 跨域,一年后的今天相关知识点基本忘光。花了一天时间重新学习,再次感谢各位前辈的帖子,特此记录如下。
--html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<! 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
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。