jquery+ajax学习笔记
实现功能:
页面输入用户名,点击按钮提交,通过js将表单数据提交到后台查询数据库,将查询到的结果展现到页面。
页面截图:
![](/attachment/201510/11/15211079_1444573168alli.png)
controller根据用户名查询指定用户例子:
-
@RequestMapping(value="getUserByName", method=RequestMethod.POST)
-
@ResponseBody
-
public User getUserByName(String username){
-
logger.info("username:"+username);
-
return userService.getUserByName(username);
-
}
查询所有用户信息:
-
@RequestMapping(value="getAllUser", method=RequestMethod.GET)
-
@ResponseBody
-
public List<User> getAllUser(){
-
return userService.getAllUser();
-
}
js例子:
-
$(function() {
-
$("form input[type=button]").click(
-
-
function() {
-
$.ajax({
-
type : 'POST',
-
url : 'getUserByName',
-
cache : false,
-
dataType : 'json',
-
data : {
-
username : $('form input[name=username]').val(),
-
},
-
success : function(user, status, xhr) {
-
$("#err").text("");
-
$("#data").html(
-
'<table border="1">'
-
+ '<tr>'
-
+ '<td>'
-
+ user.username
-
+ '</td>'
-
+ '<td>'
-
+ user.password
-
+ '</td>'
-
+ '</tr>'
-
+ '</table>');
-
},
-
error: function(status){
-
$("#data").text("");
-
$("#err").css("color", "red").text("用户不存在");
-
}
-
});
-
});
-
});
使用each循环显示数据
-
$(function(){
-
$("#btn").click(function(){
-
$.ajax({
-
type:'GET',
-
url:'getAllUser',
-
cache:false,
-
dataType:'json',
-
data:{},
-
success:function(users, status, xhr){
-
$("#err").text("");
-
$("#tab").text("");
-
var tbody = "";
-
$.each(users, function(i, user) {
-
$("#result").html("遍历对象.each的使用"+i);
-
var str = "";
-
str += "<tr><td>" +user.username+" </td><td>" + user.password +"</td></tr>";
-
tbody += str;
-
});
-
$("#tab").append(tbody);
-
},
-
error:function(){
-
$("#data").text("");
-
$("#err").css("color", "red").text("用户不存在");
-
}
-
-
});
-
});
-
-
$(document).ajaxStart(function(){
-
$("#msg").css("color", "red").text("正在努力加载中...").show();
-
}).ajaxStop(function(){
-
$("#msg").css("color", "red").text("正在努力加载中...").hide();
-
});
-
-
});
jsp例子:
-
<body>
-
<form action="" method="POST">
-
用户名:<input type="text" name="username" /> <input type="button"
-
value="查询用户信息" />
-
</form>
-
-
<div id="data"></div>
-
-
<button id="btn">查询所有用户</button>
-
-
<div id="result" style="font-size: 16px; color: red;"></div>
-
<table cellpadding=5 cellspacing=1 width=500 id="tab" border="1">
-
<tr>
-
<th>用户名 </th>
-
<th>密码</th>
-
</tr>
-
</table>
-
-
<span id="msg"></span>
-
<span id="err"></span>
-
-
</body>
阅读(1499) | 评论(0) | 转发(0) |