Ajax与Servlet处理几种数据类型

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

相关推荐