Jquery Ajax code for accessing external XML data through Handler

Source: Internet
Author: User

Jquery is very simple to use. We only need to download a script file from its official website and reference it to the page. Then you can go to your script Code Any objects and functions provided by jquery are used.
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: 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;
/// <Summary>
/// Asynchronous HTTP handler for rendering external XML source.
/// </Summary>
Public class stock: system. Web. ihttpasynchandler
{
Private Static readonly 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 ))
{
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 );
}
}
/// <Summary>
/// Do not process requests synchronously.
/// </Summary>
Public void processrequest (httpcontext context)
{
Throw new invalidoperationexception ();
}
}
/// <Summary>
/// Methods for matching hostnames to a list of safe hosts.
/// </Summary>
Public class safelist
{
/// <Summary>
/// Hard-coded list of safe hosts.
/// </Summary>
Private Static readonly ienumerable <string> hostnames = new string []
{
"Cnblogs.com ",
"Msn.com ",
"163.com ",
"Csdn.com"
};
/// <Summary>
/// Prefix each safe hostname with a period.
/// </Summary>
Private Static readonly ienumerable <string> dottedhostnames =
From hostname in hostnames
Select string. Concat (".", hostname );
/// <Summary>
/// Tests if the <paramref name = "hostname"/> matches exactly or ends with
/// Hostname from the safe host list.
/// </Summary>
/// <Param name = "hostname"> hostname to test </param>
/// <Returns> true if the hostname matches </returns>
Public bool issafe (string hostname)
{
Return matcheshostname (hostname) | matchesdottedhostname (hostname );
}
/// <Summary>
/// Tests if the <paramref name = "hostname"/> ends with a hostname from
/// Safe host list.
/// </Summary>
/// <Param name = "hostname"> hostname to test </param>
/// <Returns> true if the hostname matches </returns>
Private Static bool matchesdottedhostname (string hostname)
{
Return dottedhostnames. Any (host => hostname. endswith (host, stringcomparison. invariantcultureignorecase ));
}
/// <Summary>
/// Tests if the <paramref name = "hostname"/> matches exactly with a hostname
/// From the safe host list.
/// </Summary>
/// <Param name = "hostname"> hostname to test </param>
/// <Returns> true if the hostname matches </returns>
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: Copy code The Code is as follows: <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<SCRIPT type = "text/JavaScript" src = "jquery-1.3.2.min.js"> </SCRIPT>
</Head>
<Body>
<Div id = "con">
<Span id = "loader"> loading... </span>
</Div>
<SCRIPT type = "text/JavaScript">
Function getdata (){
$ ("# Loader"). ajaxstart (function (){
$ (This). Show ();
});
$ ("# Loader"). ajaxcomplete (function (){
$ (This). Hide ();
});
$. Ajax ({
Type: "Get ",
URL: "stock. ashx? U = http://money.service.msn.com/StockQuotes.aspx? Symbols = MSFT ",
Datatype: "XML ",
Success: function (data ){
VaR last = "";
VaR change = "";
VaR percentchange = "";
VaR volume = "";
VaR Cap = "";
VaR yearhigh = "";
VaR yearlow = "";
$ (Data). Find ('ticker '). Each (function (){
Last = $ (this). ATTR ('last ');
Change = $ (this). ATTR ('change ');
Percentchange = $ (this). ATTR ('percentchange ');
Volume = $ (this). ATTR ('Volume ');
CAP = $ (this). ATTR ('marketcap ');
Yearhigh = $ (this). ATTR ('earhigh ');
Yearlow = $ (this). ATTR ('earlow ');
Document. getelementbyid ('Con '). innerhtml = '<span> name:' + last + 'high: '+ volume + 'low:' + cap + '</span> ';
})
}
});
}
$ (Window). Load (getdata );
</SCRIPT>
</Body>
</Html>

The following is the implementation result:
name: 25.8 high: 67,502,221 low: $226,107,039,514
handler is similar in writing, so you can write a general example, you can directly use it if you need to access resources across domains in the script! The code is recorded here for your convenience.

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.