public class Ajax01 extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
JSONObject jo = new JSONObject();
jo.put("mingzi", "chenchunqiu");
jo.put("age", 33);
out.print(jo);
out.close();
}
}
function loadInfo(){
//步骤1.获取xml对象
var xhr ;//new XMLHttpRequest();
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
//发送请求
xhr.open("get", "getAjax01", true);
xhr.onreadystatechange=function(){
if(xhr.readyState==4){
alert(xhr.responseText);//xhr.responseText()获取的是json字符串
//JSON.stringify(jsonobj); //可以将json对象转换成json对符串
var jsonObj = eval(‘(‘ + xhr.responseText + ‘)‘);//可以将json字符串转换成json对象,注意需要在json字符外包裹一对小括号
alert("姓名:"+jsonObj.mingzi);
alert("年龄:"+jsonObj.age);
}
}
xhr.send(null);
}
原文:http://www.cnblogs.com/Sunnor/p/4461421.html