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 ...
随机推荐
- 深入学习jQuery自定义动画
× 目录 [1]属性对象 [2]可选参数 [3]选项参数 前面的话 很多情况下,前面介绍的jQuery动画的简单效果无法满足用户的各种需求,那么就需要对动画有更多的限制,需要采取一些高级的自定义动画来 ...
- AngularJS之Filter(二)
前言 本节我们来讲讲AngularJS中主要的部分之一,那就是过滤器,当从后台获取到的数据呈现到视图上时,此时可能需要对数据进行相应的转换,此时我们可以通过过滤器在不同页面进行不同数据的格式抓换,在A ...
- How to write perfect C code
Several days ago, I was involved in an argument about choice of C or C++. What I ignored was "l ...
- JavaSE高级之GUI编程
下面主要用到了java中的swing进行界面设计,当然java的GUI不如C#的设计的好看,不过原理还是要会的. 1. GUI Graphical User Interface 用户图形界面 a) 主 ...
- 設置Linux保留物理內存並使用 (1)
在Linux系統中可以通過memblock來設置系統保留物理內存,防止這些內存被內存管理系統分配出去. 作者: 彭東林 郵箱: pengdonglin137@163.com 平臺 硬件平臺: TQ24 ...
- Redis数据类型,以及应用场合
Redis常用的数据类型为String,Hash,List,Set等,简介如下: String 1.String 常用命令: 除了get.set.incr.decr mget等操作外,Redis还提供 ...
- 学习php中的正则表达式,PHP正则表达式基础
语法格式:位于定界符"/"之间. 较为常用的元字符包括: “+”, “*”,以及 “?”. 其中, “+”元字符规定其前导字符必须在目标对象中连续出现一次或多次, “*”元字符规定 ...
- react入门(4)
首先还是来回顾一下前三篇讲的内容 react入门(1): jsx,组件,css写法 react入门(2):事件,this.props.children,props,...other react入门(3 ...
- Python字典实现分析
背景介绍 最近使用Python开发项目为主,当使用到字典时感觉非常方便实用.那么好奇心就驱使我要搞清楚字典是怎么实现的.为了真正的搞清楚字典的实现就不得不使用C语言来实现一遍,为此我查了一些资料现在总 ...
- STM32L时钟
Four different clock sources can be used to drive the system clock (SYSCLK): 1.HSI ((high-speed inte ...