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