JQuery Ajax通過Handler訪問外部XML數(shù)據(jù)的代碼
2024-05-06 12:37:04
供稿:網(wǎng)友
JQuery的使用非常簡單,我們只需要從其官方網(wǎng)站上下載一個腳本文件并引用到頁面上即可,然后你就可以在你的腳本代碼中任意使用JQuery提供的對象和功能了。
在JQuery中使用Ajax方法異步獲取服務(wù)器資源非常簡單,讀者可以參考其官方網(wǎng)站上提供的例子http://api.jquery.com/category/ajax/。當(dāng)然,作為客戶端腳本,JQuery也會遇到跨域訪問資源的問題,什么是跨域訪問呢?簡單來說就是腳本所要訪問的資源屬于網(wǎng)站外部的資源,腳本所在的位置和資源所在的位置不在同一區(qū)域。默認(rèn)情況下,瀏覽器是不允許直接進(jìn)行資源的跨域訪問的,除非客戶端瀏覽器有設(shè)置,否則訪問會失敗。在這種情況下,我們一般都會采用在服務(wù)器端使用handler來解決,就是說在腳本和資源之間建立一個橋梁,讓腳本訪問本站點(diǎn)內(nèi)的handler,通過handler去訪問外部資源。這個是非常普遍的做法,而且操作起來也非常簡單,因為會經(jīng)常使用到,所以在此記錄一下,方便日后使用!
首先需要在網(wǎng)站中創(chuàng)建一個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;
/// <summary>
/// Asynchronous HTTP handler for rendering external xml source.
/// </summary>
public class Stock : System.Web.IHttpAsyncHandler
{
private static readonly SafeList safeList = new SafeList();
private HttpContext context;
private WebRequest request;
/// <summary>
/// Gets a value indicating whether the HTTP handler is reusable.
/// </summary>
public bool IsReusable
{
get { return false; }
}
/// <summary>
/// Verify that the external RSS feed is hosted by a server on the safe list
/// before making an asynchronous HTTP request for it.
/// </summary>
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");
}
}
/// <summary>
/// Render the response from the asynchronous HTTP request for the RSS feed
/// using the response's Expires and Last-Modified headers when caching.
/// </summary>
public void EndProcessRequest(IAsyncResult result)
{
string expiresHeader;
string lastModifiedHeader;
string rss;
using (var response = this.request.EndGetResponse(result))