Jqueryで作成したajaxサンプルを参考にしてください
3816 ワード
1、javaコード
2、htmlコード
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
public class LoginController extends AbstractController {
@SuppressWarnings("unchecked")
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request,
HttpServletResponse response) throws Exception {
Map paramMap = request.getParameterMap();
String loginName = ((String[]) paramMap.get("loginName"))[0];
String password = ((String[]) paramMap.get("password"))[0];
UserDTO user = new UserDTO();
user.setId("@^$&*!%jack");
user.setName(loginName);
user.setDescription("!@#$%^&*(dodo)");
JSONObject jsonObject = new JSONObject();
jsonObject.put("user", user);
response.getOutputStream().write(jsonObject.toString().getBytes());
return null;
}
}
2、htmlコード
<html>
<head>
<title>just for test</title>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<script type="text/javascript" src="js/jquery.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function(){
alert("hello !");
});
</script>
<p>
!
</p>
<p>
<input id="name" type="text" value=""/>
<input id="password" type="text" value=""/>
</p>
<p>
<input id="submit" type="button" value=" "/>
</p>
<table>
<tr>
<td> ID:</td>
<td><input type="text" id="userId" value=""></td>
</tr>
<tr>
<td> :</td>
<td><input type="text" id="userName" value=""></td>
</tr>
<tr>
<td> :</td>
<td><input type="text" id="userDes" value=""></td>
</tr>
</table>
<p>
<input id="getInfo" type="button" value=" "/>
</p>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
url: 'login.do',
data: {loginName:$('#name').val(), password:$('#password').val()},
success: function(result){
alert(result);
}
})
});
$("#getInfo").click(function(){
$.post("login.do",
{loginName:$('#name').val(),password:$('#password').val()},
function(data){
var jsData = eval('('+data+')');
$("#userId").attr("value",jsData.user.id);
$("#userName").attr("value",jsData.user.name);
$("#userDes").attr("value",jsData.user.description);
});
});
</script>
</body>
</html>