Ajax 使用JSON向服务器发送数据

文件一览

  • JSONExample.java
  • jsonExample.html

JSONExample.java

package ajaxbook.chap3;

import java.io.BufferedReader;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class JSONExample extends HttpServlet {

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String json = readJSONStringFromRequestBody(req);
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(json);
			String responseText = "You have a " + jsonObject.getInt("year") + " "
			+ jsonObject.getString("make") + " " + jsonObject.getString("model")+ " "
			+ "that is " + jsonObject.getString("color") + " in color";
			resp.setContentType("text/xml");
			resp.getWriter().print(responseText);
		} catch(JSONException pe) {
			System.out.println("JSONException: " + pe.toString());
		}

	}
	
	private String readJSONStringFromRequestBody(HttpServletRequest request) {
		StringBuffer json = new StringBuffer();
		String line = null;
		try {
			BufferedReader reader = request.getReader();
			while ((line = reader.readLine()) != null) {
				json.append(line);
			}
		} catch (Exception e) {
			System.out.println("Error reading JSON string: " + e.toString());
		}
		return json.toString();
	}
}

 

 

jsonExample.html

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<script language="JavaScript" src="./js/json2.js" type="text/javascript"></script>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest() {
	if (window.ActiveXObject) {
		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	} else if (window.XMLHttpRequest) {
		xmlHttp = new XMLHttpRequest();
	}
}
function doJSON() {
	var car = getCarObject();
	
	var carAsJSON = JSON.stringify(car); 
	alert("Car Object as JSON:\n "+carAsJSON);
	
	createXMLHttpRequest();
	
	var url = "JSONExample?timeStamp="+new Date().getTime();
	xmlHttp.open("POST",url,true);
	xmlHttp.onreadystatechange=handleStateChange;
	xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
	xmlHttp.send(carAsJSON);
}
function getCarObject() {
	return new Car("Dodge","Coronet R/T", 1968, "yellow");
}
function Car(make,model,year,color) {
	this.make = make;
	this.model = model;
	this.year = year;
	this.color = color;
}
function handleStateChange() {
	if (xmlHttp.readystate == 4) {
		if (xmlHttp.status == 200) {
			parseResults();
		}
	}
}
function parseResults() {
	var responseDiv = document.getElementById("serverResponse");
	if (responseDiv.hasChildNodes()) {
		responseDiv.removeChild(responseDiv.childNodes[0]);
	}
	var responseText = document.createTextNode(xmlHttp.responseText);
	responseDiv.appendChild(responseText);
}

</script>
<head>
</head>
<body>
	<h1>Select the types of pets in your home:</h1>
	<br />
	<br />
	<form action="#">
		<input type="button" value="Click here to send JSON data to the server" οnclick="doJSON()" />
	</form>
	<h2>Server Response:</h2>
	<div id="serverResponse"></div>
</body>
</html>

 其中java里要导入org.json.jar包,JavaScript要引入json2.js文件,这两个文件都在下面的附件里。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值