网站虽小,五脏俱全(干货)

前言

      最近一个朋友让帮忙做一个汇率换算的网站,用业余时间,到最后总算是实现了其需要的功能,其中也用到了一些相关的技术,把它写出来,给大家做一个参考,也给自己一个总结!

需求

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;">&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,代码如下:

       /// <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,将需要返回的数据全部装在一个数据实体类里面,然后进行序列化,返回到前台,再进行解析,后台代码如下:

 

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

总结

       至此,一个小小的功能网站就算是完成了,主要关键步骤就是汇率的获取这里,也涉及其他的技术点,就说这么多吧,觉得好的给个赞!

    源码下载:猛戳这里!

posted @ 2014-06-15 22:53  悲夢  阅读(3991)  评论(8编辑  收藏  举报