AJAX请求详解 同步异步 GET和POST
AJAX请求详解 同步异步 GET和POST
同步和异步
- //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();
- }
- }
下面就可以比较出同步和异步的差别了:
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();
- }
- }
- xmlHttpRequest.open("GET", "AjaxServlet?v1=" + value1 + "&v2=" + value2, true);//GET
- xmlHttpRequest.send(null);//GET
- 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
参考资料:
AJAX请求详解 同步异步 GET和POST的更多相关文章
- 【面试】详解同步/异步/阻塞/非阻塞/IO含义与案例
本文详解同步.异步.阻塞.非阻塞,以及IO与这四者的关联,毕竟我当初刚认识这几个名词的时候也是一脸懵. 目录 1.同步阻塞.同步非阻塞.异步阻塞.异步非阻塞 1.同步 2.异步 3.阻塞 4.非阻塞 ...
- 前后端数据交互(二)——原生 ajax 请求详解
一.ajax介绍 ajax 是前后端交互的重要手段或桥梁.它不是一个技术,是一组技术的组合. ajax :a:异步:j:js:a:和:x:服务端的数据. ajax的组成: 异步的 js 事件 其他 j ...
- 论如何把JS踩在脚下 —— JQuery基础及Ajax请求详解
一.什么是JQuery? JQuery是一种JavaScript框架,是一堆大神搞出来的能够让前端程序猿敲更少代码.实现更多功能的工具(在此,跪谢各位JQuery开发大大们!!!).JQuery的使用 ...
- 从零开始学 Web 之 Ajax(五)同步异步请求,数据格式
大家好,这里是「 从零开始学 Web 系列教程 」,并在下列地址同步更新...... github:https://github.com/Daotin/Web 微信公众号:Web前端之巅 博客园:ht ...
- $.ajax()常用方法详解(推荐)
AJAX 是一种与服务器交换数据的技术,可以在补充在整个页面的情况下更新网页的一部分.接下来通过本文给大家介绍ajax一些常用方法,大家有需要可以一起学习. 1.url: 要求为String类型的参数 ...
- jquery中的ajax方法详解
定义和用法ajax() 方法通过 HTTP 请求加载远程数据.该方法是 jQuery 底层 AJAX 实现.简单易用的高层实现见 $.get, $.post 等.$.ajax() 返回其创建的 XML ...
- $.ajax()方法详解 jquery
$.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...
- jQuery中 $.ajax()方法详解
$.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Strin ...
- $.ajax()方法详解 ajax之async属性 【原创】详细案例解剖——浅谈Redis缓存的常用5种方式(String,Hash,List,set,SetSorted )
$.ajax()方法详解 jquery中的ajax方法参数总是记不住,这里记录一下. 1.url: 要求为String类型的参数,(默认为当前页地址)发送请求的地址. 2.type: 要求为Str ...
随机推荐
- iOS开发之SQLite-C语言接口规范(一)——Ready And Open Your SQLite
为什么要搞一搞SQLite的C语言接口规范呢? 因为在做iOS开发中难免会遇到操作数据库的情况,你可以使用第三方的FMDB等,或者使用CoreData.但我们还是有必要去搞清楚如何去使用SQLite的 ...
- Git版本控制Windows版快速上手
说到版本控制,之前用过VSS,SVN,Git接触不久,感觉用着还行.写篇博文给大家分享一下使用Git的小经验,让大家对Git快速上手. 说白了Git就是一个控制版本的工具,其实没想象中的那么复杂,咱在 ...
- linux下遍历目录
遍历目录的主要思想 由于目录就是一颗树,所以遍历目录就转换为遍历一棵树.谈到树的遍历就再熟悉不过了,有树的前序.层次和后序遍历,我使用的是前序遍历,后序遍历和前序遍历本质上一样,而层次遍历要比前两个麻 ...
- 坑爹的Maven
之前没用过Maven,最近在研究Curator的时候,导入别人的工程,但是没有相应的包,需使用Maven解决依赖.于是各种折腾,最后虽然解决了,但中间的坑还不少.尽管网上也有相应的安装教程,但很多都是 ...
- C算法编程题(七)购物
前言 上一篇<C算法编程题(六)串的处理> 有些朋友看过我写的这个算法编程题系列,都说你写的不是什么算法,也不是什么C++,大家也给我提出用一些C++特性去实现问题更方便些,在这里谢谢大家 ...
- multipart数据结构
--[boundary]\r\n [headers]\r\n \r\n [content]\r\n --[boundary]\r\n [headers]\r\n \r\n [content]\r\n ...
- 关于opencv中人脸识别主函数的部分注释详解。
近段时间在搞opencv的视频人脸识别,无奈自带的分类器的准确度,实在是不怎么样,但又能怎样呢?自己又研究不清楚各大类检测算法. 正所谓,功能是由函数完成的,于是自己便看cvHaarDetectObj ...
- ar命令详解
ar 命令 用途 维护链接编辑器使用的索引库. 语法 ar [ -c ] [ -l ] [ -g | -o ] [ -s ] [ -v ] [ -C ] [ -T ] [ -z ] { ...
- 把《c++ primer》读薄(3-2 标准库vector容器+迭代器初探)
督促读书,总结精华,提炼笔记,抛砖引玉,有不合适的地方,欢迎留言指正. 标准库vector类型初探,同一种类型的对象的集合(类似数组),是一个类模版而不是数据类型,学名容器,负责管理 和 存储的元素 ...
- jQuery的事件模型
前几天自己着重读了jQuery1.11.1的源码,又结合了之前对DE事件模型的分析,最后也实现一个简陋的事件模型. jQuery的事件系统离不开jQuery的缓存系统. jQuery的第一代缓存是直接 ...