使用JQuery Ajax的JSONP方式跨域訪問是非常簡便了,缺點是隻能使用GET方式,而且靈活性非常差。
稍作小結:
原理:其實是JQuery利用HTML標籤<script>可以跨域的這一特性演變而來,所以必須應用JQuery
缺點:只能get並且調用極爲不靈活,易產生全局變量
有點:實現起來簡單,且無需複雜配置服務器端。
廢話不多說上代碼
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="../LIB/JQuery/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
function callback(obj) {
alert(JSON.stringify(obj));
}
function test() {
$.ajax({
url: "http://192.168.1.101/CommonAshx/JSONP.ashx",
//async: false,
type: 'GET',
cache: false,
//jsonp:"callback",//這裏默認是callback代表回調函數名,實際可以自己換名字
dataType: 'jsonp'//here
});
}
</script>
</head>
<body>
<input type="button" value="test" οnclick="test()" />
</body>
</html>
<%@ WebHandler Language="C#" Class="DownLoad" %>
using System;
using System.Web;
using System.IO;
public class DownLoad : IHttpHandler
{
public void ProcessRequest(HttpContext context) {
//context.Response.ContentType = "text/javascript";
string ss="{ \"asda\": 456}";
context.Response.Write("callback(" + ss + ")");
}
public bool IsReusable
{
get
{
return false;
}
}
}