为了演示通过script标签实现JSONP跨域调用,在VS的解决方案中有两个不同域的网站,客户端网站ClientJSONP的域是http://localhost:50926/ClientJSONP.aspx,处理JSONP请求的服务器网站ServerJSONP的域是http://localhost:50854/ServerPage.aspx,本示例就是为了演示从ClientJSONP跨域调用ServerJSONP,解决方案如下图所示:
客户端ClientPage.aspx的前端代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientJSONP.aspx.cs" Inherits="ClientJSONP.ClientJSONP" %>
<!DOCTYPE html>
<
html
xmlns
=
"http://www.w3.org/1999/xhtml"
>
<
head
runat
=
"server"
>
<
meta
http-equiv
=
"Content-Type"
content
=
"text/html; charset=utf-8"
/>
<
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
>
</
head
>
<
body
>
<
form
id
=
"form1"
runat
=
"server"
>
<
div
>
<
input
type
=
"button"
value
=
"跨域调用"
onclick
=
"CallCrossDomainJSONPServer('http://localhost:50854/ServerPage.aspx');"
/>
</
div
>
</
form
>
</
body
>
</
html
>
|
服务器ServerPage.aspx的后台代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ServerJSONP
{
public partial class ServerPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Charset = "utf-8";
Response.ContentType = "text/javascript";
//此例中客户端的回调函数为OnJSONPServerResponse
string callback = Request["JSONP"];
string json = "{'state':'0','msg':'hello world!'}";
//OnJSONPServerResponse({'state':'0','msg':'hello world!'})
string result = string.Format("{0}({1})", callback, json);
Response.Write(result);
Response.End();
}
}
}
|
参考:
http://blog.csdn.net/iispring/article/details/7428069
本文转自 stock0991 51CTO博客,原文链接:http://blog.51cto.com/qing0991/1717017