我在表单中有一个锚标记,我希望通过该标记将文本发布到控制器,在那里它使用发布的参数(用户名)搜索对象(用户)。
然后我想将用户名附加到“#block-showusers”。到目前为止,我有以下代码,但它不起作用。
HTML:
<form>
<div id="block-addusers" class="form-group" style="display:none">
<div id="block-showusers" style="height:25px;vertical-align:bottom"></div>
<div>
<input type="text" name="adduser" id="adduser"/>
<a href="${SITE_URL}/user/search" id="btn-adduser" class="btn btn-default">
Add
</a>
<button type="button" id="btn-canceladduser" class="btn btn-link">Cancel</button>
</div>
</div>
</form>
的JavaScript / jQuery的:
var usersBlock = "#block-addusers";
var userToAdd = "#adduser";
$("#btn-addusers").on('click', function () {
$(usersBlock).show();
$("#btn-adduser").on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
contentType: "application/json",
url: '${SITE_URL}/user/search',
data: {adduser: $(userToAdd).val()},
success: function (data) {
if (data !== "") {
$("#block-showusers").append('<div style="display:inline;margin-left:5px">' + data.username + '</div>');
}
}
});
});
});
我的“/ user”控制器类中的“搜索”方法:
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
@RequestMapping(value = "/search", method = RequestMethod.POST)
public @ResponseBody User search(@RequestParam(defaultValue = "adduser") String addUser){
return userDAO.getByUsername(addUser);
}
“getByUsername”方法:
public User getByUsername(String username) {
session=sessionFactory.openSession();
Query query = session.createQuery("SELECT u FROM User u WHERE u.username=:username");
query.setParameter("username", username);
if (query.list().size() > 0) {
session.close();
return (User) query.uniqueResult();
}
session.close();
return null;
}
任何帮助都将受到极大的赞赏。谢谢!