標籤:asp.net
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
ASP.net webClient 匯率