JS部分:
function getData(){
var url = "getData.action";
jQuery.ajax({
type: "POST",
url: url,
async: false,
success: function(data) {
var user = eval("(" + data + ")");
alert(user.userId);
alert(user.userName);
}
});
}
JAVA部分:
需要引入 json-lib-2.4-jdk15 jar包的 net.sf.json.JSON 类
import net.sf.json.JSON;
public String getData() {
JSONObject jsonobject = new JSONObject();
User u = new User();
u.setUserId("01");
u.setUserName("海洋");
JSONObject jo = jsonobject.fromObject(u);//利用JSONObject直接格式化现有VO创建json对象
/*//或者也可以这样创建json对象
JSONObject jsonobject = new JSONObject();
jsonobject.put("userId", "02");
jsonobject.put("userName", "海洋");
String jsonStr = jsonobject.toString();
*/
String jsonStr = jo.toString();
getResponse().setCharacterEncoding("utf-8");
getResponse().setContentType("text/html;charset=utf-8");
PrintWriter out;
try {
out = getResponse().getWriter();
out.print(jsonStr);
out.close();
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}