JQueryAjax code for accessing external XML data through Handler _ jquery

Source: Internet
Author: User
JQuery is a good Javascript script framework. I believe many friends in the garden are familiar with it. We will inevitably use Javascript scripts when developing Web applications, using a good script framework will greatly save our development time and achieve a lot of cool effects without any effort. JQuery is easy to use. You 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.
Using Ajax in JQuery to obtain server resources asynchronously is very simple. You can refer to the example on its official website http://api.jquery.com/category/ajax /. Of course, as a client script, JQuery will also encounter cross-origin resource access problems. What is cross-origin access? Simply put, the resource to be accessed by the script belongs to the external resources of the website. The location of the script is not in the same region as that of the resource. By default, the browser does not allow direct cross-origin access to resources. The access fails unless configured in the browser on the client. In this case, handler is usually used on the server side, that is, a bridge is established between the script and the resource to allow the script to access the handler in the site, use handler to access external resources. This is a very common practice, and the operation is very simple, because it will be used frequently, so record it here for future use!
Create a handler in the website, create a Generic Handler file in Visual Studio, and copy the following 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 Matches exactly or ends with
/// 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 Ends with a hostname from
/// 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 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 );
}
}
}


In my example, I want to obtain Microsoft's stock information on the msn site asynchronously through Ajax, and its external resource address is http://money.service.msn.com/StockQuotes.aspx? Symbols = msft. We use JQuery api to access data through Handler on the page as follows:

The Code is as follows:






Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.