一个Json例子
servlet :生成股票ID 和 price 弄成JSON的字符串传给jsp
JSP 自动刷新(异步请求) 处理JSON字符串
servlet:
package web; import java.io.IOException; import java.io.PrintWriter; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; public class Quoto extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Random r = new Random(); String stockName="s"+r.nextInt(999); double price = r.nextDouble()*100; Stock stock = new Stock(); stock.setId(stockName); stock.setPrice(price); JSONObject json = JSONObject.fromObject(stock); String str = json.toString(); System.out.print(str); out.println(str); out.close(); } }
JSP:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <html> <head> <title>Insert title here</title> <style> #d1{ width:400px; height:200px; border:1px solid black; margin-left:400px; margin-top:60px; } </style> <script type="text/javascript" src="js/prototype1.6.js"></script> <script type="text/javascript"> function getXmlHttpRequest(){ var xmlHttpRequest = null; if ((typeof XMLHttpRequest) != 'undefined') { //非ie浏览器 xmlHttpRequest = new XMLHttpRequest(); }else { //ie浏览器 xmlHttpRequest = new ActiveXObject('Microsoft.XMLHttp'); } return xmlHttpRequest; } var taskId; function allquoto(){ if($("b1").value=="stop"){ stopQuoto(); }else if($("b1").value=="start"){ quoto(); } } function quoto(){ taskId = setInterval(getPrice,500); $("b1").value="stop"; } function stopQuoto(){ clearInterval(taskId); $("b1").value="start"; } function getPrice(){ var xmlReq = getXmlHttpRequest(); xmlReq.open('post','quoto',true); xmlReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlReq.onreadystatechange=function(){ //s10010,10 if(xmlReq.readyState == 4){ var rsTxt = xmlReq.responseText; //alert(rsTxt); var stock = rsTxt.evalJSON(); $('d1').innerHTML=stock.id+": "+stock.price; } } xmlReq.send(null); } </script> </head> <body style="font-size:20pt;" onload="quoto();"> <div id="d1"> </div> <input type="button" id="b1" value="stop" style="margin-left:400px;" onclick="allquoto();"/> </body> </html>