前言
最近一個朋友讓幫忙做一個匯率換算的網站,用業余時間,到最后總算是實現了其需要的功能,其中也用到了一些相關的技術,把它寫出來,給大家做一個參考,也給自己一個總結!
需求
1.按指定需求根據最新匯率進行匯率的換算,這就需要得到最新的匯率值
2.實現QQ彈出對話功能
3.后台返回換算后的money,匯率,服務費等數據
4.實現頁面無刷新
具體實現一:前台代碼實現
前台就是界面的布局,一些HTML代碼,前台不是很熟,大家就不用挑剔了,看看界面實現就行了。主要的一個實現就是QQ彈出對話功能,QQ號碼換成自己的了。各位有需要的看官可以直接copy此功能
<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>澳元人民幣匯率計算</title> <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script src="Scripts/cc.js" type="text/javascript"></script> <style type="text/css"> #img{ background-image: url(Image/bg2.jpg); width:710px; height:250px; margin-left:40px;} .top { display:block; margin-top:5px; margin-bottom:5px; line-height:30px;} .wenzi{ font-size:12px;} .shuomingli{border-bottom: #930 2px solid; display:block; margin-top:5px; margin-bottom:5px; line-height:30px;} a{ color: #03F; text-decoration:none;} a:hover{ color:#F00;} </style> </head> <body> <div style="margin:30px auto; padding:0px; width:750px;"> <div id="img"> </div> <form id="form1" runat="server"> <ul style="list-style:none;"> <li style="background: #900; height:25px;"><span style="color:#FFF; font-size:14px;line-height:25px;"> <b>匯率計算:</b></span> </li> <li class="top"><span style="font-size:14px;">需要<span style="color:#C00;"><strong>兌換</strong></span>的<span style="color: #C00;"><strong>人民幣</strong></span>:</span><input id="txtAmount" type="text" /><span style="font-size:14px;"> 匯率為: <input id="rate" style="width:90px;" type="text" readonly="readonly"/></span><span style="font-size:14px;"> 服務費為: <input id="serverCharge" style="width:100px;" type="text" readonly="readonly"/></span><a href="tencent://message/?Menu=yes&uin=331341164&Service=200&sigT=dcfc1fdf4a83b1602a334a540048009f26d65d6f377f8dc66c97d8ecc64228e8b8441583f92b707a"><span><img style=" border:0px; vertical-align: middle; padding-bottom:5px; padding-left:2px;" src="Image/button_11.gif"></span></a> </li> <li class="top"><span style="font-size:14px;">需要<span style="color:#C00;"><strong>支付</strong></span>的<span style="color:#C00;"><strong>澳 元</stong></span>:</span><input id="txtPay" type="text" readonly="readonly"/><input id="submit" style=" background-color: #CCC" type="button" value="計算" /> <li class="top"><span style="font-size:12px;">最新匯率查詢:<a href="http://www.boc.cn/sourcedb/whpj/" target="_Blank"> 中國銀行實時匯率</a></span> </li> </ul> </form> <ul style="list-style:none;"> <li style="background: #900; height:25px;"><span style="line-height:25px; font-size:14px; color:#FFF;"><b> 兌換說明:</b></span> </li> <li class="shuomingli"><span class="wenzi">1.以上兌換所用基礎匯率均為最新匯率,可以查詢相關網站以驗證。</span> </li> <li class="shuomingli"><span class="wenzi">2.所使用匯率由兌換人民幣錢數多少決定。兌換錢數越多匯率越接近實時匯率。 </span> </li> <li class="shuomingli"><span class="wenzi">3.經以上步驟所得的價格最后再加5%的服務費即為最所需要您支付的澳元總額,若多次交易者手續費可商議而定。</span> </li> <li class="shuomingli"><span class="wenzi">4.如有問題請聯系QQ:331341164</span> </li> </ul> </div> </body> </html>
具體實現二:最新匯率的獲取
最好的實現當然是通過付費的webservices來獲取最新的實時匯率,但是咱這只是一個簡單的實現,我是通過抓取《中國銀行外匯牌價》來得到匯率值,其中用到了一個HTML解析組件:HtmlAgilityPack,大家可以去了解一下,具體實現參考了網上的一些demo,代碼如下:
/// <summary> 獲取遠程HTML內容</summary> /// <param name="url">遠程網頁地址URL</param> /// <returns>成功返回遠程HTML的代碼內容</returns> private string GetWebContent(string strUrl) { string str = ""; try { WebClient wc = new WebClient(); wc.Credentials = CredentialCache.DefaultCredentials; Encoding enc = Encoding.GetEncoding("UTF-8");// 如果是亂碼就改成 UTF-8 / GB2312 Stream res = wc.OpenRead(strUrl);//以流的形式打開URL StreamReader sr = new StreamReader(res, enc);//以指定的編碼方式讀取數據流 str = sr.ReadToEnd();//輸出(HTML代碼) res.Close(); wc.Dispose(); } catch (Exception ex) { return ""; } return str; } private DataTable GetRateTable(string strHtml) { DataTable dt = new DataTable(); DataColumn col1 = new DataColumn("Currency Name", typeof(string)); DataColumn col2 = new DataColumn("Buying Rate", typeof(string)); DataColumn col3 = new DataColumn("Cash Buying Rate", typeof(string)); DataColumn col4 = new DataColumn("Selling Rate", typeof(string)); DataColumn col5 = new DataColumn("Cash Selling Rate", typeof(string)); DataColumn col6 = new DataColumn("Middle Rate", typeof(string)); DataColumn col7 = new DataColumn("Pub Time", typeof(string)); dt.Columns.Add(col1); dt.Columns.Add(col2); dt.Columns.Add(col3); dt.Columns.Add(col4); dt.Columns.Add(col5); dt.Columns.Add(col6); dt.Columns.Add(col7); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); doc.LoadHtml(strHtml); doc.OptionOutputAsXml = true; HtmlAgilityPack.HtmlNode node = doc.DocumentNode.SelectSingleNode(".//table[tr/th=\"Currency Name\"]"); if (node == null) { return null; } HtmlAgilityPack.HtmlNodeCollection trNodeList = node.SelectNodes("tr[td]"); foreach (HtmlAgilityPack.HtmlNode trNode in trNodeList) { DataRow dr = dt.NewRow(); for (int j = 0; j < 7; j++) { HtmlAgilityPack.HtmlNodeCollection tdNodeList = trNode.SelectNodes("td"); dr[j] = tdNodeList[j].InnerText.Replace(" ", " "); ; } dt.Rows.Add(dr); } return dt; } /// <summary> /// 根據國家的代碼編號,得到匯率值 /// </summary> /// <param name="No">國家代碼</param> /// <returns></returns> private decimal GetRateByCountryNo(string No) { decimal rate = 0M; try { string html = GetWebContent("http://www.boc.cn/sourcedb/whpj/enindex.html").Trim(); DataTable dt = GetRateTable(html); if (dt == null) rate = 0M; else { for (int i = 0; i < dt.Rows.Count; i++) { if (dt.Rows[i]["Currency Name"].ToString() == No) { rate = Convert.ToDecimal(dt.Rows[i]["Cash Buying Rate"].ToString()) / 100; } } } } catch (Exception) { rate = 0M; } return rate; }
具體實現三:后台數據到前台展示
因為是返回多個數據,返回的josn格式的數據,其中用到了序列化組件:Newtonsoft.Json.Net20,將需要返回的數據全部裝在一個數據實體類里面,然后進行序列化,返回到前台,再進行解析,后台代碼如下:
public class Handler : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; WebClient web = new WebClient(); //string url = string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", "AUD", "CNY"); //string response = web.DownloadString(url); //string[] values = Regex.Split(response, ","); decimal rate = GetRateByCountryNo("AUD"); decimal amount = 0M; //decimal result = 0M; string returnStr = ""; if (rate == 0M) returnStr = ToJson("通信出錯,請稍后再試........"); else { try { ReturnModel model = new ReturnModel(); amount = System.Convert.ToDecimal(context.Request["amount"]); //decimal rate = 5.82M;//System.Convert.ToDecimal(values[1]); if (amount > 0 && amount <= 1000) { model.Rate = Math.Round(rate - 0.6M, 2); model.Result = Math.Round(amount / model.Rate, 2); model.ServerCharge = Math.Round(model.Result * 0.05M, 2); } else if (amount > 1000 && amount <= 5000) { model.Rate = Math.Round(rate - 0.4M, 2); model.Result = Math.Round(amount / model.Rate, 2); model.ServerCharge = Math.Round(model.Result * 0.05M, 2); } else if (amount > 5000) { model.Rate = Math.Round(rate - 0.3M, 2); model.Result = Math.Round(amount / model.Rate, 2); model.ServerCharge = Math.Round(model.Result * 0.05M, 2); } returnStr = ToJson(model); } catch (Exception) { returnStr = ToJson("輸入金額錯誤"); } } context.Response.Write(returnStr); } /// <summary> /// 將object對象進行序列化 /// </summary> /// <param name="t"></param> /// <returns></returns> public static string ToJson(object t) { return JsonConvert.SerializeObject(t, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include }); } }
具體實現四:ajax實現及前台數據解析
無刷新實現通過jquery 封裝的ajax來實現,直接上代碼:
$(document).ready(function () { $('#submit').click(function () { var errormsg = ""; var amount = $('#txtAmount').val(); $.ajax({ type: "POST", url: "Handler.ashx", data: { amount: amount }, contentType: "application/x-www-form-urlencoded", dataType: "json", beforeSend: function () { $('#txtPay').val("正在轉換..."); }, success: function (data) { $('#txtPay').val(data.Result); $('#rate').val(data.Rate); $('#serverCharge').val(data.ServerCharge); }, error: function (jqXHR, exception) { if (jqXHR.status === 0) { errormsg = 'Not connect.\n Verify Network.'; ; } else if (jqXHR.status == 404) { errormsg = 'Requested page not found. [404]'; ; } else if (jqXHR.status == 500) { errormsg = 'Internal Server Error [500].'; ; } else if (exception === 'parsererror') { errormsg = 'Requested JSON parse failed.'; ; } else if (exception === 'timeout') { errormsg = 'Time out error.'; ; } else if (exception === 'abort') { errormsg = 'Ajax request aborted.'; ; } else { errormsg = 'Uncaught Error.'; } alert(errormsg); } }); }); });
總結
至此,一個小小的功能網站就算是完成了,主要關鍵步驟就是匯率的獲取這里,也涉及其他的技術點,就說這么多吧,覺得好的給個贊!
源碼下載:猛戳這里!