1. 程式人生 > >JavaScript權威指南中專案程式碼 關於銀行貸款的

JavaScript權威指南中專案程式碼 關於銀行貸款的

<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>JavaScript Loan Calculator</title>
		<style>
			.output{font-weight: bold;}
			#payment{text-decoration: underline;}
			#graph{border: 1px solid black;}
			th, td{vertical-align: top;}

		</style>
	</head>

	<body>
		<table>
			<tr>
				<th>Enter Loan Data:</th>
				<td></td>
				<th>Loan Balance,Cumulative Equity,and Interest Payments</th>
			</tr>
			<tr>
				<td>Amount of the loan($):</td>
				<td><input id="amount" onchange="calculate();"/></td>
				<!--數量-->
				<td rowspan="8"><canvas id="graph" width="400" height="250"></canvas></td>
				<!--圖表-->
			</tr>
			<tr>
				<td>Annual interest(%):</td>
				<td><input id="apr" onchange="calculate();" /></td>
				<!--年百分利率-->
			</tr>
			<tr>
				<td>Repayment period (years):</td>
				<td><input id="years" onchange="calculate();" /></td>
			</tr>
			<tr>
				<td>Zipcode (to find lenders):</td>
				<td><input id="zipcode" onchange="calculate();" /></td>
				<!--郵政編碼-->
			</tr>
			<tr>
				<td>Approximate Payments:</td>
				<td><button id="years" onchange="calculate();">Calculate</button></td>
				<!--計算-->
			</tr>
			<tr>
				<td>Monthly payment:</td>
				<td>$<span class="output" id="payment"></span></td>
				<!--付款-->
			</tr>
			<tr>
				<td>Total interest:</td>
				<td>$<span class="output" id="total"></span></td>
				<!--全部的-->
			</tr>
			<tr>
				<td>Total payment:</td>
				<td>$<span class="output" id="totalinterest"></span></td>
				<!--總利息-->
			</tr>
			<tr>
				<th>Spinsors:</th>
				<td colspan="2">
					Apply for your loan with one of these fine lenders:
					<div id="lenders"></div>
					<!--貸款人-->
				</td>
			</tr>
		</table>
		<script>
			"use strict";
			function calculate(){
				//查詢文件中用於輸入輸出的元素
				var amount = document.getElementById("amount");
				var apr = document.getElementById("apr");
				var years = document.getElementById("years");
				var zipcode = document.getElementById("zipcode");
				var payment = document.getElementById("payment");
				var total = document.getElementById("total");
				var totalinterest = document.getElementById("totalinterest");
				
				//假如所有的輸入都是合法的,將從input中獲取輸入資料
				//將百分比格式轉換成小數格式,並從年利率轉化成月利率
				//將年度賠付裝換成月度賠付
				var principal = parseFloat(amount.value);
				var interest = parseFloat(apr.value)/100/12;
				var payments = parseFloat(years.value)*12;
				
				//現在計算月度賠付的資料
				var x =Math.pow(1+interest,payments);//Math.pow()進行冪次運算
				var monthly = (principal*x*interest)/(x-1);
				
				//如果結果沒有超過js能表示的數字範圍,且使用者的輸入也正確
				//這裡所展示的結果就是合法的
				if(isFinite(monthly)){
					//將數字填充到輸出欄位的位置,四捨五入到小數點後兩位數字
					payment.innerHTML = monthly.toFixed(2);
					total.innerHTML = ((monthly*payments)-principal).toFixed(2);
					totalinterest.innerHTML=((monthly*payments)-principal).toFixed(2);
					
					//將使用者輸入的資料儲存下來,這樣下次訪問時候也能取到資料
					save(amount.value,apr.value,years.value,zipcode.value);
					
					//找到並展示放貸人,但忽略網路錯誤
					try{
						//捕獲這段程式碼丟擲的所有異常
						getLenders(amount.value,apr.value,years.value,zipcode.value);
					}
					//忽略這些異常
					catch(e){}
					
					//最後,用圖表展示貸款餘額,利息和資產收益
					chart(principal,interest,monthly,payments);
				}else{
					payment.innerHTML="";
					total.innerHTML="";
					totalinterest.innerHTML="";
					chart();
				}
			}
			
			function save(amount,apr,years,zipcode){
				if(window.localStorage){//只有在瀏覽器支援的時候才支援這裡的程式碼
					localStorage.loan_amount = amount;
					localStorage.loan_apr = apr;
					localStorage.loan_years = years;
					localStorage.loan_zipcode = zipcode;
				}
			}
			
			//文件首次載入的時候,將會嘗試還原輸入欄位
			window.onload=function(){
				//如果瀏覽器支援本地儲存並且上次儲存的值是存在的
				if(window.localStorage && localStorage.loan_amount){
					document.getElementById("amount").value = localStorage.loan_amount;
					document.getElementById("apr").value = localStorage.loan_apr;
					document.getElementById("years").value = localStorage.loan_years;
					document.getElementById("zipcode").value = localStorage.loan_zipcode;
				}
			}
			
			//將使用者的輸入傳送到伺服器端指令碼返回一個本地放貸人的連線列表,在這個例子中並沒有是現在這種查詢放貸人的服務
			//但如果該服務存在,該函式會使用它
			function getLenders(amount,apr,years,zipcode){
				//如果瀏覽器不支援XMLHttpRequest物件,則退出
				if (!window.XMLHttpRequest)return;
				
				//找到要顯示放貸人列表的元素
				var ad=document.getElementById("lenders");
				if(!ad)return;//如果返回為空則退出
				
				//將使用者的輸入資料進行url編碼,並作為查詢引數附加在URL裡
				var url = "getLenders.php"+
				"?amt" + encodeURLComponent(amount)+
				"?apr" + encodeURLComponent(apr)+
				"?yrs" + encodeURLComponent(years)+
				"?zip" + encodeURLComponent(zipcode);
				
				//用XMLHttpRequest物件來提取返回資料
				var req = new XMLHttpRequest();//傳送一個新的請求
				req.open("GET",url);//通過url發起一個http get請求
				req.send(null);//不帶任何正文傳送這個請求
				
				//在返回資料之前,註冊一個事件處理函式,這個處理函式將會在伺服器的的響應返回至客戶端的時候呼叫
				//這個非同步邊城模型在客戶端js中是非常常見的
				req.onreadystatechange = function(){
					if(req.readyState == 4 && req.status == 200){
						//如果程式碼執行到這裡,說明我們得到了一個合法且完整的http響應
						var response = req.responseText;//http響應是以字串的形式呈現的
						var lenders = JSON.parse(response);//將其解析為js陣列
						
						//將陣列中的放貸人物件轉換成HTML字串的形式
						var list="";
						for(var i=0;i<lenders.length;i++){
							list += "<li><a href='"+ lenders[i].url +"'>"+lenders[i].name+"</a></li>"
						}
						
						//將資料在HTML中呈現出來
						ad.innerHTML = "<ul>"+list+"</ul>";
					}
				}
				
			}
			
			//在HTML<canvas>元素中用圖表展示月度貸款餘額,利息和資產情況	
			//如果不傳參就清空之前的圖表
			function chart(principal,interest,monthly,payments){
				var graph = document.getElementById("graph");
				graph.width = graph.width;//用一種巧妙的手法清除並重置畫布
				
				//如果不傳入引數,或者瀏覽器不支援畫布,則直接返回。
				if(arguments.length == 0 || !graph.getContext)return;
				
				//獲得畫布元素『context』物件,這個物件定義了一組繪畫API
				var g = graph.getContext("2d");
				var width = graph.width,height = graph.height; 
				
				//這裡的函式的作用是將付款數字和美元數字轉換成畫素
				function paymentToX(n){
					return n*width/payments;
				}
				function amountToY(a){
					return height - (a*height/(monthly*payments*1.05));
				}
				
				//付款資料是一條從(0,0)到(payments,monthly*payments)的直線
				g.moveTo(paymentToX(0),amountToY(0));
				g.lineTo(paymentToX(payments),amountToY(monthly*payments));
				g.lineTo(paymentToX(payments),amountToY(0));
				g.closePath();
				g.fillStyle = "#f88";
				g.fill();
				g.font = "bold 12px sans-serif";
				g.fillText("Total Interest Payments",20,20);
				
				//很多資產資料並不是線性的,很難將其反映到圖示中
				var equity = 0;
				g.beginPath();
				g.moveTo(paymentToX(0),amountToY(0));
				for(var p=1;p<=payments;p++){
					//計算出每一筆賠付的利息
					var thisMonthsINterest = (principal - equity)*interest;
					equity += (monthly -thisMonthsInterest);
					g.lineTo(paymentToX(p),amountToY(equity));
				}
				g.lineTo(paymentToX(payments),amountToY(0));
				g.closePath();
				g.fillStyle = "green";
				g.fill();
				g.fillText("Total Equity",20,35);
				
				//再次迴圈,餘額資料顯示為黑色粗線條
				var bal = principal;
				g.beginPath();
				g.moveTo(paymentToX(p),amountToY(bal));
				for(var p=1;p<=payments;p++){
					var thisMonthsInterest = bal*interest;
					bal-=(monthl - thisMonthsINterest);
					 g.lineTo(paymentToX(p),amountToY(bal));
				}
				
				g.lineWidth = 3;
				g.stroke();
				g.fillStyle ="black";
				g.fillText("Loan Balance",20,50);
				
				//將年度資料在X軸做標記
				g.textAlign = "center";
				var y = amountToY(o);
				for(var year = 1;year*12<=payments;year++){
					var x=paymentToX(year*12);
					g.fillRect(x-0.5,y-3,1,3);
					if(year == 1)g.fillText("Year",x,y-5);
					if(year %5 ==0 && year*12 !== payments)
					g.fillText(String(year),x,y-5);
				}
				
				//將賠付數額標記在右邊界
				g.textAlign = "right";
				g.textBaseline ="middle";
				var ticks = [monthly * payments,principal];
				var rightEdge = paymentToX(payments);
				for(var i=0;i<ticks.length;i++){
					var y = amountToY(ticks[i]);
					g.fillRect(rightEdge-3,y-0.5,3,1);
					g.fillText(String(ticks[i].toFixed(0)),rightEdge-5,y);
				}
			}
		</script>
	</body>

</html>