本Hack以數字形式接收股票價格,然後和用戶輸入處理以後顯示出結果。如果服務器沒有返回正確的數字,程序會顯示錯誤信息。
AJax技術的一個巨大進步就是從服務器接收不連續的數據,而不是整個頁面。有時,這些不連續信息不得不作為一個數字,而不是作為一個字符串(就像上一個Hack講的那樣)或者其他對象。JavaScript能夠很容易的將其他各式的數據轉換成數字而不需要用戶的干預,但盡管如此,用戶還是不想從服務器得到一些奇怪的數據(需要格式檢查)。
本hack檢查用戶輸入的“股票的股數”的格式為一個正確的數字格式。然後從服務器接收股票的價格。然後動態顯示出處理的結果。
Figure 1-6 浏覽器顯示圖
Figure 1-6. 顯示總量
一下是頁面的Html代碼:
“http://www.w3.org/TR/1999/REC-Html401–19991224/strict.dtd”>
下面是hack4.JS文件的代碼:
var request;
var symbol; //保存股票代碼
var numberOfShares;
function getStockPrice(sym,shs){
if(sym && shs){
symbol=sym;
numberOfShares=shs;
var url=“http://www.parkerriver.com/s/stocks?symbol=”+sym;
httpRequest(“GET”,url,true);
}
}
//event handler for XMLHttpRequest
function handleResponse( ){
if(request.readyState == 4){
alert(request.status);
if(request.status == 200){
/* Check if the return value is actually a number.
If so, multiple by the number of shares and display the result */
var stockPrice = request.responseText;
try{
if(isNaN(stockPrice)) { throw new Error(
“The returned price is an invalid number.”;}
if(isNaN(numberOfShares)) { throw new Error(
“The share amount is an invalid number.”;}
var info = “Total stock value: ”+ calcTotal(stockPrice);
displayMsg(document.
getElementById(“msgDisplay“,info,“black”;
document.getElementById(“stPrice“.style.fontSize=“0.9em”;
document.getElementById(“stPrice“.innerHtml =”price:
”+stockPrice;
} catch (err) {
displayMsg(document.getElementById(“msgDisplay”,
“An error occurred: ”+
err.message,“red”;
}
} else {
alert(
“A problem occurred with communicating between the ”+
“XMLHttpRequest object and the server program.”;
}
}//end outer if
}
/* httpRequest( )和
initReq( )函數 見hack1和2 */
function calcTotal(price){
return stripExtraNumbers(numberOfShares * price);
}
/* Strip any characters beyond a scale of four characters
past the decimal point, as in 12.3454678 */
function stripExtraNumbers(num){
//check if the number‘s already okay
//assume a whole number is valid
var n2 = num.toString( );
if(n2.indexOf(“.” == -1) { return num; }
//if it has numbers after the decimal point,
//limit the number of digits after the decimal point to 4
//we use parseFloat if strings are passed into the method
if(typeof num == “string”{
num = parseFloat(num).toFixed(4);
} else {
num = num.toFixed(4);
}
//strip any extra zeros
return parseFloat(num.toString( ).replace(/0*$/,“”);
}
function displayMsg(div,bdyText,txtColor){
//reset DIV content
div.innerHtml=“”;
div.style.backgroundColor=“yellow”;
div.style.color=txtColor;
div.innerHtml=bdyText;
}
數據處理以 handleResponse( )開始.首先代碼接收一個string,通過變量var stockPrice = request.responseText. 然後對變量stockPrice的格式進行檢查,使用的是js的函數isNaN(). JS中使用這個函數進行相關檢查很常用。例如:isNaN("goodbye")返回true,因為"goodbye"不能轉換成數字。代碼也檢查了用戶輸入的股票數量的格式。
如果有函數返回true,表示有輸入值不合法,代碼會拋出異常。這就好像在說:無法處理這些值,請修改它們。然後頁面向用戶顯示錯誤。
異常處理見hack8
calcTotal( )函數將兩個值乘起來,用以向用戶顯示結果。
使用文檔對象模型,可以動態的顯示結果,而不需要刷新頁面。
displayMsg(document.getElementById("msgDisplay"),info,"black");
document.getElementById(“stPrice“.style.fontSize=“0.9em”;
document.getElementById(“stPrice“.innerHtml =“price: ”+stockPrice;
The displayMsg( ) function is also simple. It has a parameter that represents the font color, which allows the code to set the font color "red" for error messages:
function displayMsg(div,bdyText,txtColor){
//reset DIV content
div.innerHtml=“”;
div.style.backgroundColor=“yellow”;
div.style.color=txtColor;
div.innerHtml=bdyText;
}
Figure 1-7 shows what the page looks like when the user requests a stock value.
Figure 1-7. Tallying your investment
Figure 1-8 shows an example error message, in case the user enters values that cannot be used as numbers or the server returns invalid values.
Figure 1-8. Having a bad number day