javascript 跨域问题 jsonp

转载:http://www.cnblogs.com/choon/p/5393682.html

 

demo 

   用动态创建<script></script>节点的方式实现了跨域HTTP请求,给<script>标签的src属性中的URL添加一个参数来指定回调函数的名称

服务端:

1
2
3
4
5
6
7
8
9
10
11
public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
 
    // 前端指定的回调函数名称
    var callbackFuncName = context.Request.QueryString["callback"];
    var responseData = "Hello World";
    // 回调脚本,形如:handler('responseData');
    var scriptContent = string.Format("{0}('{1}');", callbackFuncName, responseData);
    context.Response.Write(scriptContent);
}

Web客户端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>jsonp demo</title>
    <script type="text/javascript">
        // 跨域发送HTTP请求,从服务端获取字符串"Hello World"
        function getHello() {
            var script = document.createElement('script');
            script.setAttribute('src', 'http://localhost:8546/Service.ashx?callback=handler');//callback指定回调函数名称
            document.querySelector("head").appendChild(script);
        }
        // 处理函数
        function handler(data) {
            alert(data);
            // our code here...
        }
    </script>
 
</head>
<body>
    <input type="button" value="发送跨域HTTP请求,获取Hello World" onclick="getHello()" />
</body>
</html>
posted @ 2018-03-20 23:11  1点  阅读(124)  评论(0编辑  收藏  举报