1. jQuery要与服务器端交互,就得用到AJAX技术。其中提交数据至服务器的方式包括:$.ajax(),$.post(),$.get();
任何一种方法都能方便地把数据提交到服务端处理,同时也可以接收服务器端返回的数据。通常需要使用JSON来保存数据,然后把数据写入到输出面页中,同时中断任何面页跳转,即,在struts中,所有返回都以null终结。
public String execute() {
User u = new User();
u.setName(this.name);
u.setPassword(this.password);
//引入json-lib-2.3-jdk
JSONObject object = JSONObject.fromObject(u);
JSONArray js = new JSONArray();
js.add(u);
HttpServletResponse response = ServletActionContext.getResponse();
try {
PrintWriter writer = response.getWriter();
writer.write(js.toString());
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
在客户端JS程序块,使用指定的ajax接收方法来接收数据:
$.post("./testQuery.action", {name:$("#name").val(), password:$("#password").val()}, function (data) { var ul = eval('('+data+')'); $("#export span").html("abck:" + ul[0].name ); });
这样,就完成了AJAX与服务器的简单交互。