JavaScript cross-domain problem JSONP

Source: Internet
Author: User

Reprint: http://www.cnblogs.com/choon/p/5393682.html

Demo

Cross-domain HTTP requests are implemented by dynamically creating <script></script> nodes, adding a parameter to the URL in the src attribute of the <script> tag to specify the name of the callback function

Service side:

1234567891011 publicvoidProcessRequest(HttpContext context){    context.Response.ContentType = "text/plain";    // 前端指定的回调函数名称    varcallbackFuncName = context.Request.QueryString["callback"];    varresponseData = "Hello World";    // 回调脚本,形如:handler(‘responseData‘);    varscriptContent = string.Format("{0}(‘{1}‘);", callbackFuncName, responseData);    context.Response.Write(scriptContent);}

Web client:

123456789101112131415161718192021222324 <!DOCTYPEhtml><html><head><metahttp-equiv="Content-Type" content="text/html; charset=utf-8"/>    <title>jsonp demo</title>    <scripttype="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>    <inputtype="button" value="发送跨域HTTP请求,获取Hello World" onclick="getHello()" /></body></html>

JavaScript cross-domain problem JSONP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.