Ajax可以处理以下三种从Servlet返回的数据类型,分别是:Text,XML 以及JSON。下面来介绍如何用Servlet来生成以上的集中返回的数据类型,以及在前段如何用Ajax处理返回的数据。
本文以股票查询网页为例子。前段以股票代码为参数传送到服务器端,服务器端从yahoo下载关于该股票信息的cvs文件,分析该文件,并返回该股票的具体信息。
Text
Servlet,服务器端:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ String symbol= request.getParameter("symbol"); String csvString; URL url=null; URLConnection urlConnection =null; InputStreamReader inputReader =null; BufferedReader bufferedReader = null; if(symbol!=null ||symbol!="") { try{ url = new URL("http://finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=e1nl1hg"); urlConnection= url.openConnection(); inputReader = new InputStreamReader(urlConnection.getInputStream()); bufferedReader = new BufferedReader(inputReader); //get the quote as a csv string csvString = bufferedReader.readLine(); //parser StringTokenizer tokenizer = new StringTokenizer(csvString,","); String error = tokenizer.nextToken(); String name = tokenizer.nextToken(); String price = tokenizer.nextToken(); String high = tokenizer.nextToken(); String low = tokenizer.nextToken(); if(error.trim().equals("\"N/A\"")){; PrintWriter out = response.getWriter(); out.println(price); out.flush(); } else { System.out.println(symbol); System.out.println("Error symbol"+error); } }catch(MalformedURLException e){ System.out.println("URL is not well formed"); }catch (IOException e) { System.out.println("Can not open csv file"); }finally{ inputReader.close(); bufferedReader.close(); } } }
Ajax前段代码:
//an XMLHTTPRequest var xhr = null; /* * void quote() * get a quote */ function quote(){ try{ xhr = new XMLHTTPRequest(); } catch(e) { xhr= new ActiveXObject("Microsoft.XMLHTTP"); } if(xhr==null){ alert("Ajax not support by your browser"); return; } var symbol = document.getElementById("symbol").value; if(symbol==null||symbol==""){ alert("Symbol can not be empty"); return; } var url="../quote?symbol="+symbol; xhr.onreadystatechange =handler; xhr.open("GET",url,true); xhr.send(null); } function handler(){ if(xhr.readyState==4){ if(xhr.status==200){ document.getElementById("price").innerHTML = xhr.responseText; } else alert("Error with Ajax call! Code:"+xhr.status); } }
XML:
Servlet后端代码:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ //get csv file and tokenize the csv string ... ... //the same with the first part if(error.trim().equals("\"N/A\"")){ out.println("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>"); out.println("<quote>"); out.println("<name>"+name+"</name>"); out.println("<price>"+price+"</price>"); out.println("<high>"+high+"</high>"); out.println("<low>"+low+"</low>"); out.println("</quote>"); out.flush(); } else { System.out.println(symbol); System.out.println("Error symbol"+error); } }catch(MalformedURLException e){ System.out.println("URL is not well formed"); }catch (IOException e) { System.out.println("Can not open csv file"); }finally{ inputReader.close(); bufferedReader.close(); } } }
Ajax前段代码:
function handler(){ if(xhr.readyState==4){ if(xhr.status==200){ var xmlDoc=xhr.responseXML.documentElement; document.getElementById("name").innerHTML = xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue; document.getElementById("price").innerHTML = xmlDoc.getElementsByTagName("price")[0].childNodes[0].nodeValue; document.getElementById("high").innerHTML = xmlDoc.getElementsByTagName("high")[0].childNodes[0].nodeValue; document.getElementById("low").innerHTML = xmlDoc.getElementsByTagName("low")[0].childNodes[0].nodeValue; }else{ alert("Error with Ajax call! Code:"+xhr.status); } } }
JSON
Servlet后端代码:
@Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{ //define variables ... ... //same with 1. part //this is important response.setContentType("application/json;charset=UTF-8"); if(symbol!=null ||symbol!="") { try{ //get csv file and tokenize csv String if(error.trim().equals("\"N/A\"")){ JSONObject jObject = new JSONObject(); jObject.put("name", name); jObject.put("price", price); jObject.put("high", high); jObject.put("low", low); out.print(jObject); out.flush(); } else { System.out.println(symbol); System.out.println("Error symbol"+error); } }catch(MalformedURLException e){ System.out.println("URL is not well formed"); }catch (IOException e) { System.out.println("Can not open csv file"); }finally{ inputReader.close(); bufferedReader.close(); } } }
Ajax前段代码:
function handler(){ if(xhr.readyState==4){ if(xhr.status==200){ var quote = eval("("+xhr.responseText+")"); document.getElementById("code").value=xhr.responseText; var div= document.createElement("div"); var text =document.createTextNode("price:"+quote.price); div.appendChild(text); document.getElementById("quote").appendChild(div); } else alert("Error with Ajax call! Code:"+xhr.status); } }
注:关于yahoo股票中关于 参数f=e1nl1hg的值的含义,见 http://www.gummy-stuff.org/Yahoo-data.htm
相关推荐
18、在ajax中data主要有哪几种? 28 19、jQuery中ajax由几部分组成? 28 20、js和jQuery获取value值得区别 29 四、jsp/servlet部分 29 1、Tomcat的优化经验 29 2、Tomcat根目录下有哪些文件 31 3、什么是TOMCAT,怎样...
5.4 jni技术中数据类型与处理方法 5.4.1 jni技术中的本地数据类型 5.4.2 访问jni本地数据类型的方法 5.4.3 在jni本地方法中访问数组 5.4.4 jni中的主要方法 5.5 jni中的重要技术 5.5.1 局部引用与全局引用 5.5.2 ...
3、String 是最基本的数据类型吗? 8 4、float 型float f=3.4是否正确? 8 5、语句float f=1.3;编译能否通过? 8 6、short s1 = 1; s1 = s1 + 1;有什么错? 8 7、Java 有没有goto? 8 8、int 和Integer 有什么区别? 9 9...
3、String 是最基本的数据类型吗? 8 4、float 型float f=3.4是否正确? 8 5、语句float f=1.3;编译能否通过? 8 6、short s1 = 1; s1 = s1 + 1;有什么错? 8 7、Java 有没有goto? 8 8、int 和Integer 有什么区别? 9 9...
Java数据压缩与传输实例,可以学习一下实例化套按字、得到文件输入流、压缩输入流、文件输出流、实例化缓冲区、写入数据到文件、关闭输入流、关闭套接字关闭输出流、输出错误信息等Java编程小技巧。 Java数组倒置...
如数据类型转换、文件上传和下载、Struts2应用的安全性、调试与性能分析、FreeMarker、Velocily、Ajax,等等。跟随作者一道深入Struts2。聆听大量来之不易的经验之谈。你对Struts2开发框架的理解和应用水平都将更上...
30、String是最基本的数据类型吗? 22 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 22 32、是否可以继承String类? 23 33、String s = new String("xyz");...
System.out.printf() 可插入带 % 的输入类型,前两种只可以插入转义符, 不能插入 % 的数据或字符串 在 printf 里面,输出有5个部分 %[argument_index$][flags][width][.precision]conversion 以“%”开头,[第几个...
30、String是最基本的数据类型吗? 22 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 22 32、是否可以继承String类? 23 33、String s = new String("xyz");...
30、String是最基本的数据类型吗? 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 32、是否可以继承String类? 33、String s = new String("xyz");创建了几...
30、String是最基本的数据类型吗? 22 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 22 32、是否可以继承String类? 23 33、String s = new String("xyz");...
30、String是最基本的数据类型吗? 22 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 22 32、是否可以继承String类? 23 33、String s = new String(...
30、String是最基本的数据类型吗? 22 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 22 32、是否可以继承String类? 23 33、String s = new String("xyz");...
30、String是最基本的数据类型吗? 24 31、String s = "Hello";s = s + " world!";这两行代码执行后,原始的String对象中的内容到底变了没有? 24 32、是否可以继承String类? 25 33、String s = new String("xyz");...
73.8. transaction有那几种实现(事务处理)(Spring) 79 73.9. Spring IoC 79 73.10. Spring AOP面向方面编程 82 74. 项目中为什么使用SSH 85 75. Spring在SSH中的作用 86 76. weblogic 86 76.1. 如何给weblogic指定...
本网站以xp为Web平台,JSP+Ajax+Servlet+JavaBean+Hibernate为网站实现技术,建立基于MySQL数据库系统的核心动态网页,实现博客网站前台及博客个人维护管理等功能模块。 1、 系统处理的准确性和及时性:系统处理的...