Servlet获取ajax数组
首先使用setInterval()函数每隔10秒调用函数,以改动“最新价格”,原数据如下:
1、ajax发送请求,并发送数组数据:
var url="test/goldPriceProcess.action"; var data="city=ld&city=tw&city=dj"; //json数组 myXmlHttpRequest.open("post",url,true); myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); myXmlHttpRequest.onreadystatechange=manage; myXmlHttpRequest.send(data);
2、Servlet接收数据,处理后返回json数组数据:
String[] cities = request.getParameterValues("city");
PrintWriter out = response.getWriter();
StringBuilder sb = new StringBuilder();
sb.append("[");
Random ran = new Random();
for(int i=0; i<cities.length; i++){
if(i==cities.length-1){
sb.append("{\""+cities[i]+"\":"+(ran.nextInt(1000)+500)+"}]");
}else{
sb.append("{\""+cities[i]+"\":"+(ran.nextInt(1000)+500)+"},");
}
}
out.println(sb.toString()); //如[{"ld":1459},{"tw":1392},{"dj":864}]
3、ajax处理返回的数据:
function manage(){
if(myXmlHttpRequest.readyState==4 && myXmlHttpRequest.status==200){
//得到json对象
var res_obj=eval("("+myXmlHttpRequest.responseText+")");
for(var i in res_obj){
var res=res_obj[i];
for(var key in res){
$(key).innerText=res[key]; //替换“最新价格”
}
}
}
}
最终效果如下:
table的内容如下:
<table border=1 >
<tr><td>市场</td><td>最新价格$</td><td>价格涨跌</td></tr>
<tr><td>伦敦</td><td id="ld">788.7</td><td><img src="/pic/down.jpg" />211.3</td></tr>
<tr><td>台湾</td><td id="tw">854.0</td><td><img src="/pic/down.jpg" />146.0</td></tr>
<tr><td>东京</td><td id="dj">1791.0</td><td><img src="/pic/up.jpg" />791.0</td></tr>
</table>