Ajax(5):利用json做資料交換

來源:互聯網
上載者:User

工程目錄:

show.jsp :

<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%><html><head><title>Insert title here</title><script type="text/javascript" src="js/prototype1.6.js"></script><script>function getXmlHttpRequest(){var xhr=null;if((typeof XMLHttpRequest)!='undefined'){xhr=new XMLHttpRequest();}else{xhr=new ActiveXObject("Microsoft.XMLHttp");}return xhr;}var intervalId;function show(){intervalId=setInterval(getShareInfo,1000);}function stopShow(){clearInterval(intervalId);}function getShareInfo(){var xhr=getXmlHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState==4){var jsonStr=xhr.responseText;var share=jsonStr.evalJSON();$('d1').innerHTML="股票名稱:"+share.shareName+"<br>股票價格:"+share.sharePrice+"<br>時間:"+share.date;}}xhr.open("post","show",true);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.send(null);}</script></head><body onload="show();"><div style="width:250px;height:70px;border:1px solid black" id="d1"></div><input type="button" value="停止報價" onclick="stopShow();"></body></html>

Share.java :

public class Share {private String shareName;private double sharePrice;private Date date;public Date getDate() {return date;}public void setDate(Date date) {this.date = date;}public String getShareName() {return shareName;}public void setShareName(String shareName) {this.shareName = shareName;}public double getSharePrice() {return sharePrice;}public void setSharePrice(double sharePrice) {this.sharePrice = sharePrice;}public Share() {super();}public Share(String shareName, double sharePrice, Date date) {super();this.shareName = shareName;this.sharePrice = sharePrice;this.date = date;}}

DateProcessor.java :

public class DateProcessor implements JsonValueProcessor {private String pattern="yyyy-MM-dd HH:mm:ss";public void setPattern(String pattern) {this.pattern = pattern;}@Overridepublic Object processArrayValue(Object arg0, JsonConfig arg1) {Date date=(Date)arg0;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}@Overridepublic Object processObjectValue(String arg0, Object arg1, JsonConfig arg2) {Date date=(Date)arg1;SimpleDateFormat sdf=new SimpleDateFormat(pattern);return sdf.format(date);}}

ShowServlet.java :

public class ShowServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {Random random=new Random();String shareName="share"+random.nextInt(99999);double sharePrice=Math.ceil(random.nextDouble()*10);Share share=new Share(shareName,sharePrice,new Date());DateProcessor processor=new DateProcessor();JsonConfig config=new JsonConfig();config.registerJsonValueProcessor(Date.class,processor);JSONObject json=JSONObject.fromObject(share,config);response.setContentType("text/html;charset=UTF-8");PrintWriter pw=response.getWriter();pw.println(json.toString());pw.close();}}

為ShowServlet映射的url為show。

資料轉換涉及兩個過程:

① 伺服器端將Java對象Share轉換為符合json文法的字串,並發送給用戶端。

② 瀏覽器接收到符合json文法的字串,利用evalJSON( )函數將字串轉換為JavaScript對象,並及時更新頁面資料。

當然,上面的程式在實際中無意義,它僅僅為了示範json是如何做資料交換的。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.