Ajax Hacks-Hack6 接收数字数据

80酷酷网    80kuku.com

  ajax|数据Ajax Hacks-Hack6 接收数字数据

本Hack以数字形式接收股票价格,然后和用户输入处理以后显示出结果。如果服务器没有返回正确的数字,程序会显示错误信息。

Ajax技术的一个巨大进步就是从服务器接收不连续的数据,而不是整个页面。有时,这些不连续信息不得不作为一个数字,而不是作为一个字符串(就像上一个Hack讲的那样)或者其他对象。JavaScript能够很容易的将其他各式的数据转换成数字而不需要用户的干预,但尽管如此,用户还是不想从服务器得到一些奇怪的数据(需要格式检查)。

本hack检查用户输入的“股票的股数”的格式为一个正确的数字格式。然后从服务器接收股票的价格。然后动态显示出处理的结果。

Figure 1-6 浏览器显示图

Figure 1-6. 显示总量

一下是页面的HTML代码:


“http://www.w3.org/TR/1999/REC-html401–19991224/strict.dtd”>

Your total Stock Holdings

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

<

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: