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

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

同步和异步

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

  

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

public class HelloAjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet invoked!");
//mock the processing time of server
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//no cache
response.setHeader("pragma","no-cache");
response.setHeader("cache-control","no-cache");
PrintWriter out = response.getWriter();
out.println("Hello World");
out.flush();
}
}

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

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

GET和POST

     让我们把原来的程序改得复杂一点,计算两个输入框的值.
     加入两个输入框,然后在发送请求之前获取它们的值:
<body>
<input type="button" value="get content from server" onclick="ajaxSubmit();"><br>
<input type="text" value="value1" id="value1Id">
<input type="text" value="value2" id="value2Id"> <div id="div1"></div>
</body>
     服务器端获取参数值并返回计算结果:
public class HelloAjaxServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet invoked!");
process(request, response);
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost invoked!");
process(req, resp);
} private void process(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("process invoked!"); String v1 = request.getParameter("v1");
String v2 = request.getParameter("v2");
String result = String.valueOf(Integer.valueOf(v1) + Integer.valueOf(v2)); //mock the processing time of server
// try {
// Thread.sleep(5000L);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//no cache
response.setHeader("pragma", "no-cache");
response.setHeader("cache-control", "no-cache");
PrintWriter out = response.getWriter();
out.println("Hello World: " + result);
out.flush();
}
}
 
     首先用GET方法:
     GET方法的参数拼接在url的后面:
xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET
xmlHttpRequest.send(null);//GET
      
     POST方法:
xmlHttpRequest.open("POST", "AjaxServlet", true);//POST
xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null.

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

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

  完整index.jsp代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Hello Ajax</title>
<script type="text/javascript">
var xmlHttpRequest;
function ajaxSubmit() {
if (window.XMLHttpRequest) {//in JavaScript, if it exists(not null and undifine), it is true.
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else {
//very rare browsers, can be ignored.
} //also, we can handle IE5,6 first using:
/*
if (window.ActiveXObject) {
//code for IE6, IE5
}
else {
//code for others
}
*/ //send request
if (null != xmlHttpRequest) {
//get parameters from DOM
var value1 = document.getElementById("value1Id").value;
var value2 = document.getElementById("value2Id").value; //1. prepare request
// xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET
xmlHttpRequest.open("POST", "AjaxServlet", true);//POST
// XMLHttpRequest.prototype.open = function(method,url,async,user,password) {}; //2. set callback function to handle events
xmlHttpRequest.onreadystatechange = ajaxCallback; //3. do sending request action
// xmlHttpRequest.send(null);//GET //POST
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("v1=" + value1 + "&v2=" + value2);//POST requset needs params here, for GET, just leave params empty or set it to null. } } function ajaxCallback() {
//alert("test");//this alert will show several times when click the button.
if (4 == xmlHttpRequest.readyState && 200 == xmlHttpRequest.status) {
var responseText = xmlHttpRequest.responseText;
document.getElementById("div1").innerHTML = responseText;
}
}
</script> </head>
<body>
<input type="button" value="get content from server" onclick="ajaxSubmit();"><br>
<input type="text" value="" id="value1Id">
<input type="text" value="" id="value2Id"> <div id="div1"></div>
</body>
</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. javascript运动系列第五篇——缓冲运动和弹性运动

    × 目录 [1]缓冲运动 [2]弹性运动 [3]距离分析[4]步长分析[5]弹性过界[6]弹性菜单[7]弹性拖拽 前面的话 缓冲运动指的是减速运动,减速到0的时候,元素正好停在目标点.而弹性运动同样是 ...

  2. 深入学习jQuery选择器系列第五篇——过滤选择器之内容选择器

    × 目录 [1]contains [2]empty [3]parent[4]has[5]not[6]header[7]lang[8]root 前面的话 本文介绍过滤选择器中的内容选择器.内容选择器的过 ...

  3. 【原创】开源Math.NET基础数学类库使用(04)C#解析Matrix Marke数据格式

                   本博客所有文章分类的总目录:[总目录]本博客博文总目录-实时更新  开源Math.NET基础数学类库使用总目录:[目录]开源Math.NET基础数学类库使用总目录 前言 ...

  4. Jquery通过Ajax方式来提交Form表单

    今天刚好看到Jquery的ajax提交数据到服务器的方法,原文是: 保存数据到服务器,成功时显示信息. jQuery 代码: $.ajax({ type: "POST", url: ...

  5. 最大连续子序列乘积(DP)

    题目来源:小米手机2013年校园招聘笔试题 题目描述: 给定一个浮点数序列(可能有正数.0和负数),求出一个最大的连续子序列乘积. 输入: 输入可能包含多个测试样例.每个测试样例的第一行仅包含正整数 ...

  6. [OpenCV] Background subtraction

    不错的草稿.但进一步处理是必然的,也是难点所在. http://docs.opencv.org/master/d1/dc5/tutorial_background_subtraction.html#g ...

  7. 深入seajs源码系列一

    简述 前端开发模块化已经是大势所趋,目前模块化的规范有很多,众所周知的有commonJS,Module/Wrappings和AMD等,而且ES6也着手开始制定模块化机制的实现.类似于c/c++的inc ...

  8. $\LaTeX$笔记:Section 编号方式(数字、字母、罗马)&计数器计数形式修改

    $\LaTeX$系列根目录: Latex学习笔记-序 IEEE模板中Section的编号是罗马数字,要是改投其他刊物的话可能得用阿拉伯数字,所以可以在导言部分做如下修改(放在导言区宏包调用之后): \ ...

  9. 无聊的人用JS实现了一个简单的打地鼠游戏

    直入正题,用JS实现一个简单的打地鼠游戏 因为功能比较简单就直接裸奔JS了,先看看效果图,或者 在线玩玩 吧 如果点击颜色比较深的那个(俗称坏老鼠),将扣分50:如果点击颜色比较浅的那个(俗称好老鼠) ...

  10. WPF老矣,尚能饭否——且说说WPF今生未来(下):安心

    在前面的上.中篇中,我们已经可以看到园子里朋友的点评“后山见! WPF就比winform好! 激情对决”.看到大家热情洋溢的点评,做技术的我也很受感动.老实说,如何在本文收笔--WPF系列文章,我很紧 ...