天天看点

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

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

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

客户端ClientPage.aspx的前端代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ClientPage.aspx.cs" Inherits="ClientPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script type="text/javascript">
        function CallCrossDomainJSONPServer(url) {
            var oldScript = document.getElementById(url); // 如果页面中注册了调用的服务器,则重新调用
            if (oldScript) {
                oldScript.setAttribute("src", url);
                return;
            }
            var newScript = 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部分
        }
        function OnJSONPServerResponse(result) {
            alert(result);
            console.log(result);
        }
    </script>
    <%-- <script type="text/javascript" src="http://localhost:24115/MyServerJSONP/ServerPage.aspx"></script>--%>
</head>
<body>
    <input type="button" value="跨域调用" οnclick="CallCrossDomainJSONPServer('http://localhost:24115/MyServerJSONP/ServerPage.aspx');" />
</body>
</html>
           

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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class ServerPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Charset = "utf-8";
        Response.ContentType = "text/javascript";
        string callback = Request["JSONP"];//此例中客户端的回调函数为OnJSONPServerResponse
        string json = "{'state':'0','msg':'hello world!'}";
        string result = string.Format("{0}({1})", callback, json);//OnJSONPServerResponse({'state':'0','msg':'hello world!'})
        Response.Write(result);
        Response.End();

        //Response.DisableKernelCache();
        //Response.Cache.SetNoStore();
        //Response.Write("OnJSONPServerResponse('" + DateTime.Now.ToString() + "');");
        //Response.End();
    }
}
           

服务器ServerPage.aspx主要是用来处理请求的,其前端界面并不重要,所以将其前端代码设置为如下所示:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ServerPage.aspx.cs" Inherits="ServerPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
           

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