方讯标志
进入方讯技术中心
 
您现在的位置: 方讯网络 >> 网络编程 >> Ajax >> 教程正文
  Ajax Hacks-Hack 5.取得普通字符串           
Ajax Hacks-Hack 5.取得普通字符串

Ajax Hacks-Hack 5.取得普通字符串

管理天气信息,股票高价,以及其他不使用XML的时候,就是用到了普通字符串。

request 对象有时候不使用XML: request.responseText也可以很好的应用于web应用。本hack讲述用户通过选择一个股票代号,然后从服务器以字符串的格式取得该股票的价格。在下一个hack中取得股票的价格是以数字的格式。

首先看一下页面的HTML代码,其中引入了源文件hack9.js


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

Stock prices

javascript:void%200>
“getStockPrice(this.stSymbol.value);return false”>

Enter stock symbol:
“stSymbol“ size=“4”>




图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来取得服务器的响应信息,取得何种格式的信息要取决于服务器响应的信息的格式。

 
  • 上一篇教程:

  • 下一篇教程:
  • 关闭窗口
    我们的专业服务:

    乌鲁木齐网站建设、新疆网站建设、乌鲁木齐网页设计、新疆网页设计、新疆网络公司、乌鲁木齐网络公司

    乌鲁木齐网络推广、新疆网络推广、新疆网站推广
     
    为乌鲁木齐及新疆地区的企业和政府、事业单位提供专业服务:
    0991-3849127·13579879039
    域名注册 虚拟主机
    企业邮局 网站建设
    网站推广 解决方案
    OA办公
    自动化
    虚拟全景
    多媒体
    光盘
    触摸屏
  • 此栏目下没有热点教程

  • 没有任何图片教程
       
    乌鲁木齐方讯网络技术有限公司 备案序号:新ICP备05000167号  
     
    地址:乌鲁木齐市阿勒泰路30号 电话:0991-3849127 3830367