jquery ajax jsonp跨域调用实例代码跨域调用实例代码
今天研究了AJAX使用JSONP进行跨域调用的方法,发现使用GET方式和POST方式都可以进行跨域调用,这里简
单分享下,方便需要的朋友
客户端代码
复制代码 代码如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %>
<!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">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
function aa() {
$.ajax({
url: "http://localhost:12079/WebForm2.aspx",
data: "p1=1&p2=2&callback=?",
type: "post",
processData: false,
timeout: 15000,
dataType: "jsonp", // not "json" we'll parse
jsonp: "jsonpcallback",
success: function(result) {
alert(result.value1);
}
});
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
<p>
<input id="Button1" type="button" value="button" onclick="aa()" /></p>
</body>
</html>
服务器端代码
复制代码 代码如下:
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string callback = Request["callback"];
string v1="1";
string v2="2";
string response = "{\"value1\":\"" + v1 + "\",\"value2\":\"" + v2 + "\"}";
string call = callback + "(" + response + ")";
Response.Write(call);
Response.End();
}
}
客户端页面和服务器端页面在两个项目中,以便进行跨域调用测试。
跨域实例代码(需要加载jquery,页面为utf-8编码):
评论0
最新资源