ajax可以发送post或者get请求,并且可以设置同步或者异步,这里罗列了几种。其中,后台处理请求由servlet实现。
第一种方式:
- varxmlhttp=newXMLHttpRequest();
- //发送post请求,false表示发送同步请求
- xmlhttp.open("POST","AdminLogin",false);
- //设置文件的头,UTF-8应与html编码格式一致,告诉浏览器对参数编码的格式,可以解决中文传输乱码的问题
- xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
- //设置传递的参数
- xmlhttp.send("id="+id+"&password="+password);
- //显示返回结果
- alert(xmlhttp.responseText);
第二种方式(接受JSON包):
- //使用ajax方法,JS代码
- $.ajax({
- url:"GetStudentInfo",
- type:'POST',
- async:false,
- contentType:'application/json',
- mimeType:'application/json',
- success:function(data){//对返回值的处理
- $("#id").val(data.id);
- $("#name").val(data.name);
- $("#year").val(data.year);
- $("#specialty").val(data.specialty);
- $("#phone").val(data.phone);
- $("#email").val(data.email);
- },
- });
- //Servlet代码
- publicclassUser{
- publicStringid;
- publicStringname;
- publicStringyear;
- publicStringspecialty;
- publicStringphone;
- publicStringemail;
- }
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
- throwsServletException,IOException{
- ObjectMappermapper=newObjectMapper();
- Connectioncon=DBTool.getConnection();
- Useru=newUser();
- u.id="a";
- u.name="b";
- u.year="c";
- u.specialty="d";
- u.phone="e";
- u.email="f";
- response.setContentType("application/json");
- }
第三种方式(接受JSON包,返回值为集合):
- //JS代码
- $.ajax({
- url:"CheckAllStudent",
- contentType:'application/json',
- mimeType:'application/json',
- success:function(data){
- $.each(data,function(index,student){
- varstring="<tr>";
- string+="<td>"+student.id+"</td>";
- string+="<td>"+student.name+"</td>";
- string+="<td>"+student.year+"</td>";
- string+="<td>"+student.specialty+"</td>";
- string+="<td>"+student.phone+"</td>";
- string+="<td>"+student.email+"</td>";
- $("tbody").append(string);
- });
- },
- });
- //Servlet代码
- protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
- throwsServletException,IOException{
- ObjectMappermapper=newObjectMapper();
- //把相同的对象放入List中
- List<User>list=newArrayList<User>();
- Useru1,u2,u3;
- list.add(u1);
- list.add(u2);
- list.add(u3);
- response.setContentType("application/json");
- mapper.writeValue(response.getOutputStream(),list);
- }
第四种方式(ajax方法,带参数):
- $.ajax({
- url:"ShowAdvertise",
- type:'POST',
- data:{time:time},
- success:function(data){
- alert(data);
- },
- });
参考文献: