jQuery1.10.3的官方文档中,有以下几种方法实现ajax请求
试了get getJSON post,区别不大,从使用角度看,post方式最方便,至少不用去处理汉字乱码。
使用JSONObject类来封装数据,需要导入六个包如下:
commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-lang-2.4.jar
commons-logging-1.1.3.jar
commons-logging-api-1.1.jar //可选包
ezmorph-1.0.6.jar
json-lib-2.3-jdk15.jar
本次实现的是 servlet返回json格式的数据,jquery接收,显示到页面中,不啰嗦,直接上代码:
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1").click(function(){
$.post(
"servlet/Ajax",
{
username:$("#username").val(),
userpass:$("#password").val()
},
function(data){
var userInfo = data.user;
$("#Result tr:gt(0)").remove();
$("#Result").append(
"<tr><td>"+userInfo.userName+"</td><td>"+userInfo.userPass+"</td></tr>"
);},"json");
});
});
</script>
jsp页面中的 html代码:
用户名:<input type="text" id="username" />
密 码:<input type="password" id="password" />
<input id="btn1" type="submit" value="提交">
<br>
数据显示:
<table id="Result" class="clas">
<tr><td>姓名</td><td>密码</td></tr>
</table>
servlet的代码:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("执行了login servlet dopost()");
String name = request.getParameter("username");
String pass = request.getParameter("userpass");
System.out.println("post中:"+name+" "+pass);
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8"); //需设置,否则返回的汉字在页面会出问题
JSONObject jsonObject = new JSONObject();
User user = new User();
user.setUserName(name);
user.setUserPass(pass);
jsonObject.put("user", user);
PrintWriter out = response.getWriter();
out.print(jsonObject);
}
User.java bean的代码:
public class User {
private String userName;
private String userPass;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
页面提交前:
点击提交后: