<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> json.html </title>
</head>
<body>
<script src="json.js"></script>
<script>
function getCustomerInfo(){
if (window.ActiveXObject && !window.XMLHttpRequest) {
window.XMLHttpRequest=function() {
return new ActiveXObject((navigator.userAgent.toLowerCase().indexOf('msie 5') != -1) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP');
};
}//取得XMLHttpRequest对象
var url = "/jsonDemo/json?jsonStr=" + (new DBdata()).toJSONString() ;
alert(url);
var req=new XMLHttpRequest();
if (req) {
req.onreadystatechange=function() {
if (req.readyState==4 && req.status==200) {//判断状态,4是已发送,200已完成
//获得json str
var jss = req.responseText;
alert("request.responseText : " + req.responseText);
//加载到 javascript 类中 string -> jsBean
var jsobj = eval('(' + jss + ')');
document.getElementById('text').value = jsobj.name ;
document.getElementById('text2').value = jsobj.avg ;
}
}
req.open('GET', url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(null);//发送参数如果有参数req.send("username="+user_name);用request取得
}
}
function DBdata(){
this .name = 'BurceLee';
this .avg = 23 ;
this .init = function (){
alert('OK');
}
}
</script>
<INPUT id ="text" type ="text" >
<INPUT id ="text2" type ="text" >
<INPUT id ='a' type ="button" onclick ="getCustomerInfo()" value ="click">
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.*;
import org.apache.commons.jxpath.JXPathContext;
public class Json extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse rpo)throws ServletException,IOException{
rpo.setCharacterEncoding("GBK");
req.setCharacterEncoding("GBK");
rpo.setContentType("text/html; charset=GBK");
PrintWriter out = rpo.getWriter() ;
// 得到 url 传入数据
String jsonStr = req.getParameter("jsonStr") ;
System.out.println("************************jsonStr :" + jsonStr);
/*
* {"name":"BurceLee",
* "avg" : 29
* }
*
*
*
* 以下注释部分原本想通过url传入的数据转变成json对象
* 并将其解析成一个map,对其中key=“ave”的值加一
* 后返回给前台jsp。不知为什么系统总是报
* java.lang.NoClassDefFoundError
* at net.sf.json.JSONObject.fromObject(JSONObject.java:154)
* 的异常
* 暂且将这段代码注释掉,还希望高手们帮助解决一下。
*/
/*JSONObject jso = JSONObject.fromObject(jsonStr);
JXPathContext jx = JXPathContext.newContext(jso);
try {
jx.setValue("./avg", jx.getValue("./avg + 1 ") );
} catch (Exception e) {e.printStackTrace();}
//以 jsonString 传出
out.print(jso.toString());
*/
out.print("{\"name\":\"BurceLee11\",\"avg\":29}");
}
}
程序源码见附件中