網站雖小,五臟俱全(乾貨)

前言

      最近一個朋友讓幫忙作一個匯率換算的網站,用業餘時間,到最後總算是實現了其須要的功能,其中也用到了一些相關的技術,把它寫出來,給你們作一個參考,也給本身一個總結!javascript

需求

1.按指定需求根據最新匯率進行匯率的換算,這就須要獲得最新的匯率值css

2.實現QQ彈出對話功能html

3.後臺返回換算後的money,匯率,服務費等數據java

4.實現頁面無刷新node

具體實現一:前臺代碼實現

前臺就是界面的佈局,一些HTML代碼,前臺不是很熟,你們就不用挑剔了,看看界面實現就好了。主要的一個實現就是QQ彈出對話功能,QQ號碼換成本身的了。各位有須要的看官能夠直接copy此功能jquery

<!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;">&nbsp;&nbsp;<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;">&nbsp;匯率爲:&nbsp;<input id="rate"  style="width:90px;" type="text" readonly="readonly"/></span><span style="font-size:14px;">&nbsp;服務費爲:&nbsp;<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>&nbsp;&nbsp;</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">&nbsp;&nbsp;中國銀行實時匯率</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>&nbsp;&nbsp;兌換說明:</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,代碼以下:web

       /// <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("&nbsp;", " "); ;
                }
                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,將須要返回的數據所有裝在一個數據實體類裏面,而後進行序列化,返回到前臺,再進行解析,後臺代碼以下:ajax

 

    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來實現,直接上代碼:json

 

$(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);
            }
        });
    });
});

總結

       至此,一個小小的功能網站就算是完成了,主要關鍵步驟就是匯率的獲取這裏,也涉及其餘的技術點,就說這麼多吧,以爲好的給個贊!app

    源碼下載:猛戳這裏!

相關文章
相關標籤/搜索