为了演示通过script标签实现JSONP跨域调用,在VS的解决方案中有两个不同域的网站,客户端网站ClientJSONP的域是http://localhost:50926/ClientJSONP.aspx,处理JSONP请求的服务器网站ServerJSONP的域是http://localhost:50854/ServerPage.aspx,本示例就是为了演示从ClientJSONP跨域调用ServerJSONP,解决方案如下图所示:
客户端ClientPage.aspx的前端代码:
<%@PageLanguage="C#"AutoEventWireup="true"CodeBehind="ClientJSONP.aspx.cs"Inherits="ClientJSONP.ClientJSONP"%> <!DOCTYPEhtml> <htmlxmlns="http://www.w3.org/1999/xhtml"> <headrunat="server"> <Metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/> <title>跨域调用客户端</title> <scripttype="text/javascript"> functionCallCrossDomainJSONPServer(url){ varoldScript=document.getElementById(url);//如果页面中注册了调用的服务器,则重新调用 if(oldScript){ oldScript.setAttribute("src",url); return; } varnewScript=document.createElement("script");//如果未注册该服务器,则注册并请求之 newScript.setAttribute("type","text/javascript"); newScript.setAttribute("src",url+"?JSONP=OnJSONPServerResponse"); newScript.setAttribute("id",url); document.head.appendChild(newScript); //注意,此处也可以写成document.body.appendChild,但是不能写成document.appendChild //因为脚本只能位于head部分或者body部分 } functionOnJSONPServerResponse(result){ alert(result); console.log(result); } </script> </head> <body> <formid="form1"runat="server"> <div> <inputtype="button"value="跨域调用"onclick="CallCrossDomainJSONPServer('http://localhost:50854/ServerPage.aspx');"/> </div> </form> </body> </html>
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Web; usingSystem.Web.UI; usingSystem.Web.UI.WebControls; namespaceServerJSONP { publicpartialclassServerPage:System.Web.UI.Page { protectedvoidPage_Load(objectsender,EventArgse) { Response.Charset="utf-8"; Response.ContentType="text/javascript"; //此例中客户端的回调函数为OnJSONPServerResponse stringcallback=Request["JSONP"]; stringjson="{'state':'0','msg':'helloworld!'}"; //OnJSONPServerResponse({'state':'0','msg':'helloworld!'}) stringresult=string.Format("{0}({1})",callback,json); Response.Write(result); Response.End(); } } }
参考:
http://blog.csdn.net/iispring/article/details/7428069
原文链接:https://www.f2er.com/json/289548.html