要實現JSONP跨域訪問,首先就要了解什麼是跨域?然後JSONP與JSON的關系? 1、什麼是跨域? 跨域簡單的說就是一個域名下的程序和另一個域名下的程序做數據交互。比如說:現有一個http://www.zq.com和http://www.qt.com兩個獨立的網站,要實現從後一個網站向前一個網站中取數據。把做為數據來源的當作服務端,把去獲取數據的當作客戶端,實現面向服務的編程。 在動態網頁當中,最重要的一項就是取數據。如果是在同一個項目中,將網站掛在同一個域名下,這種情況下無論是前台Ajax還是後台直接取數據都非常方便。但是如果像上面的兩個網站一樣,在不同的域名下,那麼取數據就變得非常麻煩(現在有Web Servers和WCF實現面向服務的編程) 2、什麼情況下用JSONP做跨域訪問? 當要用Ajax從其它的項目中取數據時候。如果是在後台中從其它網站取數據,可用Web Servers或WCF等技術來實現。 3、JSONP和JSON的關系? JSON是一種基於文本的數據交互方式,而JSONP是基於JSON的使用方式。從使用上簡單的講就是:不跨域 用JSON實現A jax和後台數據交互; 跨域 用JSONP實現Ajax和其它域中程序做數據交互。 4、$.ajax實現JSONP
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PRequest.aspx.cs" Inherits="jsonP.PRequest" %>
<!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>
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/json2.js" type="text/javascript"></script>
<script type="text/javascript">
function aa() {
var person = {};//自定義數組
person.name = "aName";
person.age = 18;
//console.log(JSON.stringify(person));
$.ajax({
url: "http://localhost:58878/jp.ashx",//另一個域中的程序
type: "get",
dataType: "jsonp",//預期返回類型為JSONP
data: { 'person': JSON.stringify(person) },
jsonp: "callback", //在一個jsonp請求中重寫回調函數的名字,可省
success: function (rt) {
var result = JSON.parse(rt);
//console.log(result);
$("#lb").html(result.Name + "<br />" + result.Age);
}, error: function (e) {
//console.log(e);
}
});
}
</script>
</head>
<body>
<input id="Button1" type="button" value="取值" onclick="aa()" />
<div id = "lb" style="width: 90px;height: 90px;background-color: red"></div>
</body>
</html>
通過分析不難發現其與JSON寫法上的不同: 1、url上的細微差異,在JSONK中常是直接某個路徑下的處理程序,而JSONP是寫別的網站(域)下的處理代碼程序路徑。但要注意:JSON也能這樣寫 2、dataTypy現在處理的是JSONP而不是JSON 其它傳參數據 ,接參數等和JSON並無二異 數據源部分
using System.Web;
namespace PResponse
{
/// <summary>
/// Summary description for jp
/// </summary>
public class jp : IHttpHandler
{
public class person
{
public string Name { get; set; }
public int Age { get; set; }
}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string callback = context.Request["callback"];//callback不能少
string ca = context.Request["person"];
person b = Newtonsoft.Json.JsonConvert.DeserializeObject<person>(ca);
string response = "{\"Name\":\"" + b.Name + "\",\"Age\":\"" + b.Age + "\"}";
string re = Newtonsoft.Json.JsonConvert.SerializeObject(response);
string call = callback + "(" + re + ")";//response和re相同,前面的callback不能少
context.Response.Write(call);
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
這樣就實現了跨域訪問 5、說明 1)之所以在前台取數據要分JSON和JSONP,是因為JavaScript 的同源策略