管理天气信息,股票高价,以及其他不使用XML的时候,就是用到了普通字符串。
request 对象有时候不使用XML: request.responseText也可以很好的应用于web应用。本Hack讲述用户通过选择一个股票代号,然后从服务器以字符串的格式取得该股票的价格。在下一个Hack中取得股票的价格是以数字的格式。
首先看一下页面的HTML代码,其中引入了源文件Hack9.js
“http://www.w3.org/TR/1999/REC-html401–19991224/strict.dtd”>
Stock prices
图1-5是页面在firefox中的显示。用户输入股票代号如“GRMN”,然后点击取得股票价格按钮;程序向服务器发送股票代号信息,然后以字符串的格式从服务器取得相应的价格,并显示出来。
函数getStockPrice是请求处理函数。函数从页面取得股票代号,并取得从服务器返回的股票价格(是用请求对象同服务器组建通信,取得实时的股票价格)。代码如下:
var request;
var symbol; //保存股票代号
function getStockPrice(sym){
symbol=sym;
if(sym){
var url=“http://www.parkerriver.com/s/stocks?symbol=”+sym;
httpRequest(“GET”,url,true);
}
}
//XMLHttpRequest 事件处理函数
function handleResponse( ){
if(request.readyState == 4){
if(request.status == 200){
/* Grab the result as a string */
var stockPrice = request.responseText;
var info = “«The price is: $“+stockPrice+“»”;
document.getElementById(“stPrice“.style.fontSize=“0.9em”;
document.getElementById(“stPrice”.style.
backgroundColor=“yellow”;
document.getElementById(“stPrice”.innerHTML=info;
} else {
alert(“A problem occurred with communicating between ”+
“the XMLHttpRequest object and the server program.”;
}
}//end outer if
}
/* 在Hack #1 察看httpRequest( ) 函数的代码;在这里省略 */
函数getStockPrice里边调用了函数httpRequest,该函数负责设置request对象。如果读者已经看了本章的前几个Hacks,就会明白handleResponse封装了更重要的动作。
function handleResponse(){
if(request.readyState == 4){
if(request.status == 200){
/*Grab the result as a string*/
var stockPrice = request.responseText;
var info = “«The price is: $“+stockPrice+“»”;
document.getElementById(“stPrice“.style.fontSize=“0.9em”;
document.getElementById(“stPrice“.style.backgroundColor=“yellow”;
document.getElementById(“stPrice”.innerHTML =info;
} else {
alert(“A problem occurred with communicating between the XMLHttpRequest object and the server program.”;
}
}//end outer if
}
当请求完成后(即:request.readyState 的值为4),HTTP响应状态为400(表示请求成功),代码使用request.responseText来取得服务器的响应。代码然后是用DOM来显示相关信息。
document.getElementById("stPrice").style.fontSize="0.9em";
document.getElementById(“stPrice“.style.backgroundColor=“yellow”;
document.getElementById(“stPrice”.innerHTML =info;
本Hack讲的是如何通过request.responseText来取得服务器的响应信息,取得何种格式的信息要取决于服务器响应的信息的格式。
< <script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>