- doPost()代码:
//封装成JSON格式,返回给浏览器
StringBufferbuffer=newStringBuffer();
//这里我们拼接成4个对象
buffer.append("({");
for(Map.Entry<String,Stock>entry:map.entrySet()){
Stringid=entry.getKey();
Stockstock=entry.getValue();
buffer.append(id).append(":{yesterday:").append(stock.getYesterday()).append(",today:").append(stock.getToday()).append(",high:").append(stock.getHighest()).append(",low:").append(stock.getLowest()).append(",current:").append(stock.getCurrent()).append(",range:'").append(stock.getRange()).append("'}").append(",");
}
//消除最后一个逗号
buffer.deleteCharAt(buffer.lastIndexOf(","));
//最后补上括号
buffer.append("})");
//返回给浏览器
response.getWriter().write(buffer.toString());
- 拼接成的JSON数据:
({
3:{yesterday:333.3,today:333.48,high:333.48,low:333.3,current:333.48,range:'0.05%'},
2:{yesterday:222.2,today:223.46,high:223.46,low:222.2,current:223.46,range:'0.57%'},
1:{yesterday:1110.1,today:1109.73,high:1110.1,low:1109.73,current:1109.73,range:'-0.03%'},
4:{yesterday:1133.5,today:1135.49,high:1135.49,low:1133.5,current:1135.49,range:'0.18%'}
})
客户端分析之一
客户端要做的就是显示数据,每隔两秒就和服务器进行一次交互
- 用到Ajax和setInterval()方法
html代码
使用div嵌套span和a标签来进行显示,span装载的就是服务端返回json的current数据
<bodyonload="show()">
<div>
<ahref="#">百度:</a>
<spanid="1"></span>
</div>
<div>
<ahref="#">阿里巴巴:</a>
<spanid="2"></span>
</div>
<div>
<ahref="#">腾讯:</a>
<spanid="3"></span>
</div>
<div>
<ahref="#">谷歌:</a>
<spanid="4"></span>
</div>
</body>
javaScript代码
- 解析JSON,并设置span的内容
functionshow(){
getStock();
//每两秒就取一次数据
setInterval(getStock,2000);
}
varhttpRequest;
functiongetStock(){
//力求是最新的响应数据,如果存在httpRequest,那么将上次的httpRequest终止
if(httpRequest){
httpRequest.abort();
}
httpRequest=newXMLHttpRequest();
httpRequest.open("GET","Refresh",true);
httpRequest.onreadystatechange=callBackFunction;
httpRequest.send(null);
}
functioncallBackFunction(){
if(httpRequest.readyState==4){
if(httpRequest.status==200){
//得到服务器端返回的JSON数据
vartext=httpRequest.responseText;
//解析成JavaScript对象
varjson=eval(text);
//遍历出每个JSON对象【也就是json的id】
for(varidinjson){
//得到每个stock对象
varstock=json[id];
//将当前的价格设置到span节点里面
document.getElementById(id).innerHTML=stock.current;
//比较当前价格和昨天开盘价格,如果大于就是红色,小于就是绿色
if(stock.current>stock.yesterday){
document.getElementById(id).style.color='red';
}else{
document.getElementById(id).style.color='green';
}
}
}
}
}
- 效果