加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

通过script标签实现JSONP跨域调用

发布时间:2020-12-16 19:02:35 所属栏目:百科 来源:网络整理
导读:为了演示通过script标签实现JSONP跨域调用,在VS的解决方案中有两个不同域的网站,客户端网站ClientJSONP的域是http://localhost:50926/ClientJSONP.aspx,处理JSONP请求的服务器网站ServerJSONP的域是http://localhost:50854/ServerPage.aspx,本示例就是为

为了演示通过script标签实现JSONP跨域调用,在VS的解决方案中有两个不同域的网站,客户端网站ClientJSONP的域是http://localhost:50926/ClientJSONP.aspx,处理JSONP请求的服务器网站ServerJSONP的域是http://localhost:50854/ServerPage.aspx,本示例就是为了演示从ClientJSONP跨域调用ServerJSONP,解决方案如下图所示:

wKioL1ZWfKCQhsucAAB2cSag67k696.jpg


客户端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>

服务器ServerPage.aspx的后台代码:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读