jQuery 的使用非常直觀:從官網下載一個腳本文件並引入頁面,就能在代碼中自由調用它提供的各項能力。
在 jQuery 中用 Ajax 異步獲取服務器資源同樣簡單,讀者可以參考官網的 Ajax 分類示例:https://api.jquery.com/category/ajax/。不過作為客戶端腳本,jQuery 也會遇到跨域訪問的限制。所謂跨域,通俗地說就是腳本要訪問的資源位於站點之外,腳本所在位置與資源所在位置不在同一區域。出於安全考慮,瀏覽器默認禁止直接跨域訪問,除非客戶端另有設置,否則請求會失敗。
面對這種情況,常見的解法是在服務器端建立一個 handler 作為橋樑:讓腳本先訪問本站點內的 handler,再由 handler 去請求外部資源,最後把結果回傳給腳本。這是相當普遍且易用的做法,因為經常會用到,這裡記錄下來備查。
首先在 Visual Studio 中新建一個 Generic Handler 文件,粘貼以下代碼:
<%@ WebHandler Language="C#" Class="WebApplication1.Stock" %>
namespace WebApplication1
{
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Collections.Generic;
using System.Linq;
public class Stock : System.Web.IHttpAsyncHandler
{
private static readonly SafeList safeList = new SafeList();
private HttpContext context;
private WebRequest request;
public bool IsReusable
{
get { return false; }
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
var u = context.Request.QueryString["u"];
var uri = new Uri(u);
if (safeList.IsSafe(uri.DnsSafeHost))
{
this.context = context;
this.request = HttpWebRequest.Create(uri);
return this.request.BeginGetResponse(cb, extraData);
}
else
{
throw new HttpException(204, "No content");
}
}
public void EndProcessRequest(IAsyncResult result)
{
string expiresHeader;
string lastModifiedHeader;
string rss;
using (var response = this.request.EndGetResponse(result))
{
expiresHeader = response.Headers["Expires"];
lastModifiedHeader = response.Headers["Last-Modified"];
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream, true))
{
rss = reader.ReadToEnd();
}
}
var output = this.context.Response;
output.ContentEncoding = Encoding.UTF8;
output.ContentType = "text/xml;";
output.Write(rss);
var cache = output.Cache;
cache.VaryByParams["u"] = true;
DateTime expires;
var hasExpires = DateTime.TryParse(expiresHeader, out expires);
DateTime lastModified;
var hasLastModified = DateTime.TryParse(lastModifiedHeader, out lastModified);
cache.SetCacheability(HttpCacheability.Public);
cache.SetOmitVaryStar(true);
cache.SetValidUntilExpires(true);
DateTime expireBy = DateTime.Now.AddHours(1);
if (hasExpires && expires.CompareTo(expireBy) <= 0)
cache.SetExpires(expires);
else
cache.SetExpires(expireBy);
if (hasLastModified)
cache.SetLastModified(lastModified);
}
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
}
public class SafeList
{
private static readonly IEnumerable<string> hostnames = new string[]
{
"cnblogs.com",
"msn.com",
"163.com",
"csdn.com"
};
private static readonly IEnumerable<string> dottedHostnames =
from hostname in hostnames
select string.Concat(".", hostname);
public bool IsSafe(string hostname)
{
return MatchesHostname(hostname) || MatchesDottedHostname(hostname);
}
private static bool MatchesDottedHostname(string hostname)
{
return dottedHostnames.Any(host => hostname.EndsWith(host, StringComparison.InvariantCultureIgnoreCase));
}
private static bool MatchesHostname(string hostname)
{
return hostnames.Contains(hostname, StringComparer.InvariantCultureIgnoreCase);
}
}
}
這個例子想通過 Ajax 異步取得 msn 站點上微軟的股票信息,外部資源地址為 https://money.service.msn.com/StockQuotes.aspx?symbols=msft。頁面上如此調用:
function getData() {
$("#loader").ajaxStart(function() { $(this).show(); });
$("#loader").ajaxComplete(function() { $(this).hide(); });
$.ajax({
type: "GET",
url: "Stock.ashx?u=https://money.service.msn.com/StockQuotes.aspx?symbols=msft",
dataType: "xml",
success: function(data) {
$(data).find('ticker').each(function() {
var last = $(this).attr('last');
var volume = $(this).attr('volume');
var cap = $(this).attr('marketcap');
document.getElementById('con').innerHTML = '<span>name:' + last + ' high:' + volume + ' low:' + cap + '</span>';
});
}
});
}
$(window).load(getData);
實現結果示例:name:25.8 high:67,502,221 low:$226,107,039,514
Handler 的寫法大同小異,因此完全可以整理成一個通用模板,日後遇到腳本需要跨域訪問資源時直接套用即可。謹記此處記錄,方便查閱。