javascript:void%200>
“getStockPrice(this.stSymbol.value,this.numShares.value);return false”>
Enter stock symbol:
Enter share amount:
当用户点击Get Total Value按钮,动作引发表单元素的提交事件。getStockPrice函数用来处理事件。函数取得股票符号以及股票数量作为参数。The return false part of the event-handling code cancels the browser’s typical submission of the form values to the URL specified by the form tag’s action attribute. 下面是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