AJAx使用json与后台交互数据之JSONObject
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript">var xmlHttpReq;//创建一个XmlHttpRequest对象function createXmlHttpRequest() {if (window.XMLHttpRequest) {xmlHttpReq = new XMLHttpRequest();//非IE浏览器} else if (window.ActiveXObject) {xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");//IE浏览器}}function check(name){if(name!=""){alert(name);//1.创建一个XmlHttpRequest对象createXmlHttpRequest();//2.调用XMLHTTPRequest对象的 open方法(),//初始化XMLHttpRequest组件//处理缓存问题 url后面再加个时间参数,保证每次请求的url都不同var url = "jsonObject";var query = "name="+name;xmlHttpReq.open("POST",url,true);// "Get"是请求方式,//url向后台服务器发送请求的url//true 代表使用异步请求, 可选参数,默认为true //3.注册回调函数xmlHttpReq.onreadystatechange=callBack;//callBack 为自定义的回调函数的名字 注意:后面没有括号//当xmlHttpReq对象的readystate状态改变时自动触发 回调函数callBack//4.把请求发送到服务器 xmlHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttpReq.send(query); //post请求}else{alert("请输入数据");}}function callBack(){//alert("readyState:"+xmlHttpReq.readyState);if(xmlHttpReq.readyState==4){//ajax引擎初始化成功if(xmlHttpReq.status==200){//与tomcat(服务器)交互成功,http协议成功alert("xmlHttpReq.status:"+xmlHttpReq.status);var json = xmlHttpReq.responseText;//通过responseText 属性,取出服务器端返回的数据alert(json);var obj = eval('(' + json+ ')');//通过eval函数把jsonObject对象转换js中的对象alert("obj"+obj);alert(obj.name);alert(obj.age);alert(obj.sex);}}}</script></head><body><p align="center">省市二级联动</p><table align="center"><tr><td>省份</td><td><input type="text" onblur="check(this.value)"></td><td><span id="sp1"></span></td></tr></table></body></html>?后台json代码:
package com.wepull.servlet;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.JSONArray;import net.sf.json.JSONObject;public class JsonObjectServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubdoPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");String name = request.getParameter("name");System.out.println("ajax传来的name:"+name); PrintWriter pw = response.getWriter();JSONObject jsonObj = new JSONObject();jsonObj.put("name", "小希子");jsonObj.put("age", new Integer(21));jsonObj.put("sex", "男");System.out.println(jsonObj);pw.println(jsonObj);}}?