1.什麼是跨域請求:
服務器A上的一個頁面,要請求服務器B上的一個處理程序,這就叫做跨域請求
本次的測試頁面為:
處理程序kimhandler.ashx,如下:
%@ WebHandler Language="C#" Class="KimHandler" %>
using System;
using System.Web;
public class KimHandler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string msg = "{\"name\":\"kim\",\"gender\":\"男\",\"age\":24}";
context.Response.Write(msg);
}
public bool IsReusable {
get {
return false;
}
}
}
另一張處理程序handler.ashx如下:
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string callbackName = context.Request.Params["callbackFun"];
string msg = callbackName+ "({\"name\":\"kim\",\"age\":\"18\"});";
context.Response.Write(msg);
}
public bool IsReusable {
get {
return false;
}
}
}
2.Ajax無法實現跨域請求
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script>
var requestUrl = "http://qxw1192430265.my3w.com/kimhandler.ashx";
window.onload = function () {
document.getElementById("btnAjax").onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("get", requestUrl, true);
xhr.setRequestHeader("If-Modified-Since", 0);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var res = xhr.responseText;
alert(res);
}
}
xhr.send(null);
}
}
</script>
</head>
<body>
<input type="button" id="btnAjax" value="點擊" />
</body>
</html>
查看監視器,發現沒有返回任何請求報文體

3.使用script標簽,可以實現跨域請求
測試代碼如下:
<!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="http://qxw1192430265.my3w.com/kimhandler.ashx"></script> </head> <body> </body> </html>
查看監視器,可以看到,有返回請求報文體

在用json格式看下

4.使用js方式,在浏覽器端,讀取響應是數據
測試代碼如下,注意換了一個處理程序
<!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>
function getData(data) {
for (var key in data) {
alert(data[key]);
}
}
</script>
<script src="http://qxw1192430265.my3w.com/handler.ashx?callbackFun=getData"></script>
</head>
<body>
</body>
</html>
通過後台代碼,可知

然後在監視器上看看


發現在浏覽器端,彈出了kim還有18
5.使用Jq來實現跨域請求(內部原理就是為我們創建了一個script標簽)
代碼如下
<!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="jquery-1.9.0.js"></script>
<script>
var requestUrl = "http://qxw1192430265.my3w.com/handler.ashx";
window.onload = function () {
document.getElementById("btnJq").onclick = function() {
$.ajax(requestUrl, {
type: "get", //請求方式
dataType: "jsonp", //數據發送類型
jsonp: "callbackFun", //服務器端接收的參數
jsonpCallback: "fun", //js處理方法
success: function () {
alert("成功");
}
});
}
}
function fun(data) {
for (var key in data) {
alert(data[key]);
}
}
</script>
</head>
<body>
<input type="button" id="btnJq" value="Jq按鈕" />
</body>
</html>
點擊按鈕後,可以看到效果,再看下監視器

以上所述就是本文的全部內容了,希望大家能夠喜歡。