zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    Codeforces 723d [暴力dfs]
    Codeforces 723e [图论][欧拉回路]
    Hihocoder 1035 [树形dp]
    Codeforces 721C [dp][拓扑排序]
    Codeforces 721D [贪心]
    info
    关于string操作
    Floyd求最小环 HDU1599
    Codeforces Round #572 (Div. 2) B Number Circle
    A. XXXXX
  • 原文地址:https://www.cnblogs.com/guangzhou11/p/8613532.html
Copyright © 2011-2022 走看看