The use of jquery is simple, we just need to download a script file from its official web site and reference it to the page, and then you can use the objects and functions that jquery provides in your scripting code.
Using AJAX methods to get server resources asynchronously in jquery is very simple, and readers can refer to the examples provided on their official website http://api.jquery.com/category/ajax/. Of course, as a client-side script, jquery also encounters cross-domain access to resources, and what is Cross-domain access? Simply put, the resource that the script is accessing is a resource outside the site, and the location of the script is not in the same area as the resource. By default, browsers are not allowed to have cross-domain access to resources directly, unless the client browser has settings, the access fails. In this case, we generally use handler on the server side to solve, that is, a bridge between the script and resources, so that the script access to the site handler, through the handler to access external resources. This is a very common practice, but also very simple to operate, because it will be used frequently, so here to record, easy to use later!
First you need to create a handler in your Web site, a new generic handler file in Visual Studio, and copy the following code:
Copy Code code 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 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's external RSS feed is hosted by a server on the safe list
Before making a 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 (URI, Safelist.issafe. 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 or exactly with a
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 the
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 with a exactly
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 get the Microsoft Stock information on the MSN site asynchronously via Ajax, and the external resource address is http://money.service.msn.com/StockQuotes.aspx?symbols=msft, We use the jquery API on the page to access data through handler:
Copy Code code as follows:
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title></title>
<script type= "Text/javascript" src= "Jquery-1.3.2.min.js" ></script>
<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 (' Yearhigh ');
Yearlow = $ (this). attr (' Yearlow ');
document.getElementById (' con '). InnerHTML = ' <span>name: ' + Last + ' High: ' + volume + ' Low: ' + cap + ' </sp An> ';
})
}
});
}
$ (window). Load (getData);
</script>
</body>
The following are the results of the implementation:
name:25.8 high:67,502,221 low:$226,107,039,514
Handler's writing is basically the same, so you can write a generic example that you can use directly in the future if you need to access resources across domains in a script! The code is documented here for easy access.