ajax传递json数据在java web当中是常用到的,基于这一点,本人写了一个小例子仅供参考
js
function tijiao() {
var xuehao = $("#xuehao").val();
var password = $("#mima").val();
$.ajax({
type : "get",//数据发送的方式(post 或者 get)
url : "/aa/login.do",//要发送的后台地址
data : {
xuehao : xuehao,
password : password
},//要发送的数据(参数)格式为{'val1':"1","val2":"2"}
dataType : "json",//后台处理后返回的数据格式
success : function(data) {//ajax请求成功后触发的方法
alert('请求成功');
},
error : function(msg) {//ajax请求失败后触发的方法
alert(msg);//弹出错误信息
}
});
}
sevlet
@WebServlet(name = "login", urlPatterns = { "/login.do" })
public class login extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
String xuehao = req.getParameter("xuehao");
String password = req.getParameter("password");
System.out.println("输出学号:" + xuehao);
System.out.println("输出密码::" + password);
PrintWriter out = resp.getWriter();
String data = "[{name:\"胡阳\",age:24},{name:\"胡阳\",age:23}]";// 构建的json数据
out.println(data);
}
}