AJAX请求详解 同步异步 GET和POST

  
  上一篇博文(http://www.cnblogs.com/mengdd/p/4191941.html)介绍了AJAX的概念和基本使用,附有一个小例子,下面基于这个例子做一些探讨.
 

同步和异步

     在准备请求的时候,我们给open方法里传入了几个参数,其中第三个参数为true时,表示是异步请求:
  1. //1. prepare request
  2. xmlHttpRequest.open("GET", "AjaxServlet", true);
  3. // XMLHttpRequest.prototype.open = function(method,url,async,user,password) {};

  

  为了模拟服务器的响应,并且不使用缓存内容,我们把服务器代码改成如下,加了5秒延时:

  1. public class HelloAjaxServlet extends HttpServlet {
  2.  
  3. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. System.out.println("doGet invoked!");
  5. //mock the processing time of server
  6. try {
  7. Thread.sleep(5000L);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. //no cache
  12. response.setHeader("pragma","no-cache");
  13. response.setHeader("cache-control","no-cache");
  14. PrintWriter out = response.getWriter();
  15. out.println("Hello World");
  16. out.flush();
  17. }
  18. }

  下面就可以比较出同步和异步的差别了:

  xmlHttpRequest.open()方法,第三个参数设置为async=true时,异步:
  点击按钮后过了5秒出现Hello World字样,但是这5秒过程中页面中的其他地方都是不受影响的,可以操作.
 
  xmlHttpRequest.open()方法,第三个参数设置为async=false时,同步:
  同样是点击按钮5秒后出现Hello World字样,但是这5秒中,按钮是不可点击状态,页面不可做其他操作.
  当使用同步设置时,其实不需要写回调函数,直接把响应的操作放在后面的语句即可.
  注:不推荐使用async=false.
 
 

GET和POST

     让我们把原来的程序改得复杂一点,计算两个输入框的值.
     加入两个输入框,然后在发送请求之前获取它们的值:
  1. <body>
  2. <input type="button" value="get content from server" onclick="ajaxSubmit();"><br>
  3. <input type="text" value="value1" id="value1Id">
  4. <input type="text" value="value2" id="value2Id">
  5.  
  6. <div id="div1"></div>
  7. </body>
     服务器端获取参数值并返回计算结果:
  1. public class HelloAjaxServlet extends HttpServlet {
  2.  
  3. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  4. System.out.println("doGet invoked!");
  5. process(request, response);
  6. }
  7.  
  8. @Override
  9. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  10. System.out.println("doPost invoked!");
  11. process(req, resp);
  12. }
  13.  
  14. private void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
  15. System.out.println("process invoked!");
  16.  
  17. String v1 = request.getParameter("v1");
  18. String v2 = request.getParameter("v2");
  19. String result = String.valueOf(Integer.valueOf(v1) + Integer.valueOf(v2));
  20.  
  21. //mock the processing time of server
  22. // try {
  23. // Thread.sleep(5000L);
  24. // } catch (InterruptedException e) {
  25. // e.printStackTrace();
  26. // }
  27. //no cache
  28. response.setHeader("pragma", "no-cache");
  29. response.setHeader("cache-control", "no-cache");
  30. PrintWriter out = response.getWriter();
  31. out.println("Hello World: " + result);
  32. out.flush();
  33. }
  34. }
 
     首先用GET方法:
     GET方法的参数拼接在url的后面:
  1. xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET
  2. xmlHttpRequest.send(null);//GET
  1.       
     POST方法:
  1. xmlHttpRequest.open("POST", "AjaxServlet", true);//POST
  2. xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null.

  注意,使用POST方法提交,在请求发送之前,必须要加上如下一行:

  1. xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

  完整index.jsp代码:

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Hello Ajax</title>
  5. <script type="text/javascript">
  6. var xmlHttpRequest;
  7. function ajaxSubmit() {
  8. if (window.XMLHttpRequest) {//in JavaScript, if it exists(not null and undifine), it is true.
  9. // code for IE7+, Firefox, Chrome, Opera, Safari
  10. xmlHttpRequest = new XMLHttpRequest();
  11. } else if (window.ActiveXObject) {
  12. // code for IE6, IE5
  13. xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
  14. } else {
  15. //very rare browsers, can be ignored.
  16. }
  17.  
  18. //also, we can handle IE5,6 first using:
  19. /*
  20. if (window.ActiveXObject) {
  21. //code for IE6, IE5
  22. }
  23. else {
  24. //code for others
  25. }
  26. */
  27.  
  28. //send request
  29. if (null != xmlHttpRequest) {
  30. //get parameters from DOM
  31. var value1 = document.getElementById("value1Id").value;
  32. var value2 = document.getElementById("value2Id").value;
  33.  
  34. //1. prepare request
  35. // xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET
  36. xmlHttpRequest.open("POST", "AjaxServlet", true);//POST
  37. // XMLHttpRequest.prototype.open = function(method,url,async,user,password) {};
  38.  
  39. //2. set callback function to handle events
  40. xmlHttpRequest.onreadystatechange = ajaxCallback;
  41.  
  42. //3. do sending request action
  43. // xmlHttpRequest.send(null);//GET
  44.  
  45. //POST
  46. xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  47. xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null.
  48.  
  49. }
  50.  
  51. }
  52.  
  53. function ajaxCallback() {
  54. //alert("test");//this alert will show several times when click the button.
  55. if (4 == xmlHttpRequest.readyState && 200 == xmlHttpRequest.status) {
  56. var responseText = xmlHttpRequest.responseText;
  57. document.getElementById("div1").innerHTML = responseText;
  58. }
  59. }
  60. </script>
  61.  
  62. </head>
  63. <body>
  64. <input type="button" value="get content from server" onclick="ajaxSubmit();"><br>
  65. <input type="text" value="" id="value1Id">
  66. <input type="text" value="" id="value2Id">
  67.  
  68. <div id="div1"></div>
  69. </body>
  70. </html>

index.jsp

参考资料:

  圣思园张龙老师JavaWeb视频教程64 POST与GET方式提交Ajax请求的区别,深度解读HTTP协议.

AJAX请求详解 同步异步 GET和POST的更多相关文章

  1. 【面试】详解同步/异步/阻塞/非阻塞/IO含义与案例

    本文详解同步.异步.阻塞.非阻塞,以及IO与这四者的关联,毕竟我当初刚认识这几个名词的时候也是一脸懵. 目录 1.同步阻塞.同步非阻塞.异步阻塞.异步非阻塞 1.同步 2.异步 3.阻塞 4.非阻塞 ...

  2. 前后端数据交互(二)——原生 ajax 请求详解

    一.ajax介绍 ajax 是前后端交互的重要手段或桥梁.它不是一个技术,是一组技术的组合. ajax :a:异步:j:js:a:和:x:服务端的数据. ajax的组成: 异步的 js 事件 其他 j ...

  3. 论如何把JS踩在脚下 —— JQuery基础及Ajax请求详解

    一.什么是JQuery? JQuery是一种JavaScript框架,是一堆大神搞出来的能够让前端程序猿敲更少代码.实现更多功能的工具(在此,跪谢各位JQuery开发大大们!!!).JQuery的使用 ...

  4. 从零开始学 Web 之 Ajax(五)同步异步请求,数据格式

    大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...

  5. $.ajax()常用方法详解(推荐)

    AJAX 是一种与服务器交换数据的技术,可以在补充在整个页面的情况下更新网页的一部分.接下来通过本文给大家介绍ajax一些常用方法,大家有需要可以一起学习. 1.url: 要求为String类型的参数 ...

  6. jquery中的ajax方法详解

    定义和用法ajax() 方法通过 HTTP 请求加载远程数据.该方法是 jQuery 底层 AJAX 实现.简单易用的高层实现见 $.get, $.post 等.$.ajax() 返回其创建的 XML ...

  7. $.ajax()方法详解 jquery

    $.ajax()方法详解   jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...

  8. jQuery中 $.ajax()方法详解

    $.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Strin ...

  9. $.ajax()方法详解 ajax之async属性 【原创】详细案例解剖——浅谈Redis缓存的常用5种方式(String,Hash,List,set,SetSorted )

    $.ajax()方法详解   jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...

随机推荐

  1. iOS开发之SQLite-C语言接口规范(一)——Ready And Open Your SQLite

    为什么要搞一搞SQLite的C语言接口规范呢? 因为在做iOS开发中难免会遇到操作数据库的情况,你可以使用第三方的FMDB等,或者使用CoreData.但我们还是有必要去搞清楚如何去使用SQLite的 ...

  2. Git版本控制Windows版快速上手

    说到版本控制,之前用过VSS,SVN,Git接触不久,感觉用着还行.写篇博文给大家分享一下使用Git的小经验,让大家对Git快速上手. 说白了Git就是一个控制版本的工具,其实没想象中的那么复杂,咱在 ...

  3. linux下遍历目录

    遍历目录的主要思想 由于目录就是一颗树,所以遍历目录就转换为遍历一棵树.谈到树的遍历就再熟悉不过了,有树的前序.层次和后序遍历,我使用的是前序遍历,后序遍历和前序遍历本质上一样,而层次遍历要比前两个麻 ...

  4. 坑爹的Maven

    之前没用过Maven,最近在研究Curator的时候,导入别人的工程,但是没有相应的包,需使用Maven解决依赖.于是各种折腾,最后虽然解决了,但中间的坑还不少.尽管网上也有相应的安装教程,但很多都是 ...

  5. C算法编程题(七)购物

    前言 上一篇<C算法编程题(六)串的处理> 有些朋友看过我写的这个算法编程题系列,都说你写的不是什么算法,也不是什么C++,大家也给我提出用一些C++特性去实现问题更方便些,在这里谢谢大家 ...

  6. multipart数据结构

    --[boundary]\r\n [headers]\r\n \r\n [content]\r\n --[boundary]\r\n [headers]\r\n \r\n [content]\r\n ...

  7. 关于opencv中人脸识别主函数的部分注释详解。

    近段时间在搞opencv的视频人脸识别,无奈自带的分类器的准确度,实在是不怎么样,但又能怎样呢?自己又研究不清楚各大类检测算法. 正所谓,功能是由函数完成的,于是自己便看cvHaarDetectObj ...

  8. ar命令详解

    ar 命令 用途 维护链接编辑器使用的索引库. 语法 ar [  -c ] [  -l ] [  -g | -o ] [  -s ] [  -v ] [  -C ] [  -T ] [  -z ] { ...

  9. 把《c++ primer》读薄(3-2 标准库vector容器+迭代器初探)

    督促读书,总结精华,提炼笔记,抛砖引玉,有不合适的地方,欢迎留言指正. 标准库vector类型初探,同一种类型的对象的集合(类似数组),是一个类模版而不是数据类型,学名容器,负责管理 和 存储的元素 ...

  10. jQuery的事件模型

    前几天自己着重读了jQuery1.11.1的源码,又结合了之前对DE事件模型的分析,最后也实现一个简陋的事件模型. jQuery的事件系统离不开jQuery的缓存系统. jQuery的第一代缓存是直接 ...