WebClient汇率
简介
有个需求网站中需要美元汇率。这里通过webClient实现,这种还是比较简单,不涉及js跨域问题。还有注意点最好将查到的数据放在缓存中,缓存有效期设为1小时,防止频繁问汇率网站给锁死。
实现
1、现将一个aspx页面,后台代码写法,通过访问该页面时传参 url获得汇率的接口。
protected void Page_Load(objectsender, EventArgs e)
{
System.Net.WebClient wc = new System.Net.WebClient();
wc.Encoding = System.Text.Encoding.GetEncoding("UTF-8");
string requestUrl = Request.QueryString["url"].ToString();
string result = string.Empty;
string cacheKey = requestUrl;
System.Web.Caching.Cache cache =Cache;
if (cache[cacheKey] == null)
{
result = wc.DownloadString(requestUrl).ToString();
cache.Insert(cacheKey, result, null, DateTime.MaxValue, TimeSpan.FromSeconds(3600));
}
else
{
result = cache[cacheKey].ToString();
}
Response.Write(result);
Response.End();
}
2、创建展示数据的用户控件,用户控件前台代码,后台返回的是整个页面,前台通过js取出自己想要的数据。
<span style="font-size:18px;"> $.get('上个页面url?url=http://srh.bankofchina.com/search/whpj/search.jsp?pjname=1316', function (resp) {
var temp = $(resp).find('.BOC_maintr:eq(1)').find('td:eq(2)').text();
var rate = (temp / 100).toFixed(4);
var result = " 1美元=" + rate + "元";
$('#exchRate').html(result);
});</span>
3、那个页面需要展示,只有注册用户控件应用就可以了。
总结
网站中需要一些小功能可以这么做,如天气预报等等…….注意页面需要引用jquery