ajax发送get、post请求

前端之家收集整理的这篇文章主要介绍了ajax发送get、post请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ajax可以发送post或者get请求,并且可以设置同步或者异步,这里罗列了几种。其中,后台处理请求由servlet实现。

第一种方式:

[javascript] view plain copy print ?
  1. varxmlhttp=newXMLHttpRequest();
  2. //发送post请求,false表示发送同步请求
  3. xmlhttp.open("POST","AdminLogin",false);
  4. //设置文件的头,UTF-8应与html编码格式一致,告诉浏览器对参数编码的格式,可以解决中文传输乱码的问题
  5. xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
  6. //设置传递的参数
  7. xmlhttp.send("id="+id+"&password="+password);
  8. //显示返回结果
  9. alert(xmlhttp.responseText);


第二种方式(接受JSON包):

[javascript] view plain copy print ?
  1. //使用ajax方法,JS代码
  2. $.ajax({
  3. url:"GetStudentInfo",
  4. type:'POST',
  5. async:false,
  6. contentType:'application/json',
  7. mimeType:'application/json',
  8. success:function(data){//对返回值的处理
  9. $("#id").val(data.id);
  10. $("#name").val(data.name);
  11. $("#year").val(data.year);
  12. $("#specialty").val(data.specialty);
  13. $("#phone").val(data.phone);
  14. $("#email").val(data.email);
  15. },
  16. });

  1. //Servlet代码
  2. publicclassUser{
  3. publicStringid;
  4. publicStringname;
  5. publicStringyear;
  6. publicStringspecialty;
  7. publicStringphone;
  8. publicStringemail;
  9. }
  10. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  11. throwsServletException,IOException{
  12. ObjectMappermapper=newObjectMapper();
  13. Connectioncon=DBTool.getConnection();
  14. Useru=newUser();
  15. u.id="a";
  16. u.name="b";
  17. u.year="c";
  18. u.specialty="d";
  19. u.phone="e";
  20. u.email="f";
  21. response.setContentType("application/json");
  22. }

第三种方式(接受JSON包,返回值为集合):
[javascript] view plain copy print ?
  1. //JS代码
  2. $.ajax({
  3. url:"CheckAllStudent",
  4. contentType:'application/json',
  5. mimeType:'application/json',
  6. success:function(data){
  7. $.each(data,function(index,student){
  8. varstring="<tr>";
  9. string+="<td>"+student.id+"</td>";
  10. string+="<td>"+student.name+"</td>";
  11. string+="<td>"+student.year+"</td>";
  12. string+="<td>"+student.specialty+"</td>";
  13. string+="<td>"+student.phone+"</td>";
  14. string+="<td>"+student.email+"</td>";
  15. $("tbody").append(string);
  16. });
  17. },
  18. });
  1. //Servlet代码
  2. protectedvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  3. throwsServletException,IOException{
  4. ObjectMappermapper=newObjectMapper();
  5. //把相同的对象放入List中
  6. List<User>list=newArrayList<User>();
  7. Useru1,u2,u3;
  8. list.add(u1);
  9. list.add(u2);
  10. list.add(u3);
  11. response.setContentType("application/json");
  12. mapper.writeValue(response.getOutputStream(),list);
  13. }


第四种方式(ajax方法,带参数):

[javascript] view plain copy print ?
  1. $.ajax({
  2. url:"ShowAdvertise",
  3. type:'POST',
  4. data:{time:time},
  5. success:function(data){
  6. alert(data);
  7. },
  8. });

参考文献:

jQuery ajax - ajax() 方法

原文链接:https://www.f2er.com/ajax/164906.html

猜你在找的Ajax相关文章