Home > Web Front-end > JS Tutorial > JQuery Ajax code to access external XML data through Handler_jquery

JQuery Ajax code to access external XML data through Handler_jquery

WBOY
Release: 2016-05-16 18:25:55
Original
804 people have browsed it

Using JQuery is very simple. We only need to download a script file from its official website and reference it on the page. Then you can use the objects and functions provided by JQuery in your script code.
It is very simple to use Ajax method to asynchronously obtain server resources in JQuery. Readers can refer to the examples provided on its official website http://api.jquery.com/category/ajax/. Of course, as a client script, JQuery will also encounter the problem of cross-domain access to resources. What is cross-domain access? To put it simply, the resources to be accessed by the script belong to resources outside the website, and the location of the script and the location of the resources are not in the same area. By default, browsers do not allow direct cross-domain access to resources. Unless the client browser has settings, the access will fail. In this case, we usually use handlers on the server side to solve the problem, which means to establish a bridge between the script and the resources, allowing the script to access the handler in this site and access external resources through the handler. This is a very common method, and it is also very simple to operate. Because it will be used frequently, I will record it here for future use!
First you need to create a handler in the website, create a new Generic Handler file in Visual Studio, and copy the following code:

Copy code The code is as follows:

<%@ 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;
///
/// Asynchronous HTTP handler for rendering external xml source.
///

public class Stock : System.Web.IHttpAsyncHandler
{
private static readonly SafeList safeList = new SafeList();
private HttpContext context;
private WebRequest request;
///
/// Gets a value indicating whether the HTTP handler is reusable.
///

public bool IsReusable
{
get { return false; }
}
///
/// Verify that the external RSS feed is hosted by a server on the safe list
/// before making an asynchronous HTTP request for it.
///

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");
}
}
///
/// Render the response from the asynchronous HTTP request for the RSS feed
/// using the response's Expires and Last-Modified headers when caching.
///

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;"; // "application/rss xml; charset=utf-8";
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.SetSlidingExpiration(false);
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);
}
}
///
/// Do not process requests synchronously.
///

public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException();
}
}
///
/// Methods for matching hostnames to a list of safe hosts.
///

public class SafeList
{
///
/// Hard-coded list of safe hosts.
///

private static readonly IEnumerable hostnames = new string[]
{
"cnblogs.com",
"msn.com",
"163.com",
"csdn.com"
};
///
/// Prefix each safe hostname with a period.
///

private static readonly IEnumerable dottedHostnames =
from hostname in hostnames
select string.Concat(".", hostname);
///
/// Tests if the matches exactly or ends with a
/// hostname from the safe host list.
///

/// Hostname to test
/// True if the hostname matches
public bool IsSafe(string hostname)
{
return MatchesHostname(hostname) || MatchesDottedHostname(hostname);
}
///
/// Tests if the ends with a hostname from the
/// safe host list.
///

/// Hostname to test
/// True if the hostname matches
private static bool MatchesDottedHostname(string hostname)
{
return dottedHostnames.Any(host => hostname.EndsWith(host, StringComparison.InvariantCultureIgnoreCase));
}
///
/// Tests if the matches exactly with a hostname
/// from the safe host list.
///

/// Hostname to test
/// True if the hostname matches
private static bool MatchesHostname(string hostname)
{
return hostnames.Contains(hostname, StringComparer.InvariantCultureIgnoreCase);
}
}
}

我给出的例子中是想通过Ajax异步取得msn站点上微软的股票信息,其外部资源地址为http://money.service.msn.com/StockQuotes.aspx?symbols=msft,我们在页面上这样使用JQuery api通过Handler来访问数据:
复制代码 代码如下:









loading...





下面是实现的结果:
name:25.8 high:67,502,221 low:$226,107,039,514
  Handler的写法基本都大同小异,因此可以写成一个通用的例子,以后如遇到在脚本中需要跨域访问资源时便可以直接使用!代码记录于此,方便查阅。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template