原生的Ajax
Ajax(Asynchronous Javascript And XML:异步Javascript和XML)在2005年2月被提出。不过Ajax并不是一种新的语言或技术。实际上,它由几种已知的技术组合而成。Ajax技术的核心是XMLHttpRequest。Ajax就是通过XMLHttpRequest对象来发送异步的请求。
1、js原生Ajax的开发步骤(4步)
-
创建Ajax引擎对象--XMLHttpRequest对象(可以参考w3cSchool 手册代码案例);
XMLHttpRequest对象属于javascript中的一个对象,存在ajax引擎中。
不同浏览器提供不同的支持
//IE6, IE5
new ActiveXObject("Microsoft.XMLHTTP");
//IE7+, Firefox, Chrome, Opera, Safari
new XMLHttpRequest();
范例代码:
let xmlHttp; function createXMLHttpRequest() { //判断浏览器是否支持XMLHttpRequest if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlHttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } return xmlHttp; } xmlHttp=createXMLHttpRequest();2.为XMLHttpRequest对象绑定监听(监听服务器,将数据响应给引擎),对返回数据进行处理;
实例代码:
xmlHttp.onreadystatechange =function(){
// 请求完成,接收后台服务器的响应,判断数据是否正确
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
// 响应有效
alert("响应返回了..." + xmlHttp.responseText);
}
};
3.绑定提交地址;
使用open()方法建立与服务器的连接.
open(method,url, asynch)
参数:
- method :请求方式: get post。
- url 请求地址
- async 同步?异步? 默认异步:true ,false表示同步
示例代码:
xmlHttp.open("GET","/ajax/helloworld?name=zhangsan");//ajax/helloworld表示servlet的URL地址
//xmlHttp.open("POST","/ajax/helloworld");//ajax/helloworld表示servlet的URL地址
// post发送参数前,需要设置编码格式,否则后台获取不到数据,post请求是模拟form表单提交数据
//application/x-www-form-urlencoded 表示form表单操作类型
//xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
4.发送请求;
使用send()方法向服务器端发送数据.
示例代码:
客户端向服务器提交数据
1、get方式发送数据
xmlHttp.open("GET","url?key=value"); // 参数已经在url上
xmlHttp.send();
2、post方式发送数据
// 不需要写参数
xmlHttp.open("POST","url");
// post发送参数前,需要设置编码格式
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
// 发送post数据
xmlHttp.send("name=xxx&pwd=xxx");
2、js原生的Ajax代码实现
【案例】js原生的Ajax演示
【需求】
- 点击页面按钮发送请求到后台Servlet;
- 后台Servlet接收数据后,给出响应;
- 页面接收响应数据;
2.1 Ajax原生的GET和POST请求
【Ajax原生的GET请求】
【ajaxGetDemo.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax的get请求</title>
</head>
<body>
<button id="btn">发送get请求</button>
</body>
<script>
//给按钮绑定事件
document.getElementById("btn").onclick = function () {
//ajax发送get请求
//1.创建xhr XMLHttpRequest ajax引擎 发送请求
var xhr = new XMLHttpRequest();;
//2.监听请求和响应状态 请求 响应
xhr.onreadystatechange = function () {
//请求和响应 OK
if(xhr.readyState == 4 && xhr.status == 200){
//接收响应数据 ajax能够接收的响应数据类型:1.字符串 2.xml
var responseText = xhr.responseText;
alert(responseText);
}
}
//3.设置请求参数 get post 数据
//1.method get post
//2.url 请求地址
//3.async 同步?异步? 默认异步==true
xhr.open("GET","/ajaxGetServlet?name=张三&age=19",true);
//4.发送请求
xhr.send();
}
</script>
</html>
【AjaxGetServlet.java】
//处理响应乱码
response.setContentType("text/html;charset=utf-8");
//接收请求数据
String name = request.getParameter("name");
String age = request.getParameter("age");
//输出
System.out.println("name="+name+",age="+age);
//响应数据
response.getWriter().print("请求已经收到");
说明:
1)对于不同的浏览器获取ajax核心对象不一致,所以我们要针对不同的浏览器来获取ajax的核心对象:
//1.创建xhr XMLHttpRequest ajax引擎 发送请求
var xhr;
//普通浏览器 Chrome FireFox
//判断浏览器中是否含有XMLHttpRequest对象
if(window.XMLHttpRequest) {
//说明浏览器中有XMLHttpRequest对象 IE7+, Firefox, Chrome, Opera, Safari
xhr = new XMLHttpRequest();
}else {
///说明浏览器中没有有XMLHttpRequest对象
//ie5 ie6
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
2)onreadystatechange :触发器。 作用:客户端发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态。每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
readyState属性是XMLHttpRequest对象的属性,它是表示当前ajax引擎和服务器交互过程中的变化情况,也就是对象状态(表示请求状态),通过5个数字体现状态变化:
0 : 表示客户端建立了XMLHttpRequest对象,但并没有和服务器进行交互(请求未初始化).
1 : 表示客户端已经调用XMLHttpRequest对象中的open方法,打开了和服务器的连接(请求正在加载).
2 : 表示客户端已经调用XMLHttpRequest对象中的send方法,发送出了请求数据(请求已加载).
3 : 表示服务器已经处理完请求但还没有给客户端响应数据(交互中).
4 : 表示服务器响应数据正常结束(请求完成).
status:status属性是XMLHttpRequest 对象中的用于表示服务器响应数据的状态码的描述.服务器返回的HTTP状态码.200 表示服务器响应数据一切正常.500 服务器内部出错。和学习http协议中的响应的状态码一致。
需求:在servlet中添加代码 1/0来模拟服务器异常。然后修改页面的代码。
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理响应乱码
response.setContentType("text/html;charset=utf-8");
//接收请求数据
String name = request.getParameter("name");
String age = request.getParameter("age");
//模拟异常
int i=1/0;
//输出
System.out.println("name="+name+",age="+age);
//响应数据
response.getWriter().print("请求已经收到");
}
页面代码:
//2、为XMLHttpRequest对象绑定监听(监听服务器,将数据响应给引擎),对返回数据进行处理
xmlHttp.onreadystatechange=function () {
//判断请求和响应都成功
if(xmlHttp.readyState == 4 && xmlHttp.status == 200){
//接收响应数据 ajax能够接收的响应数据类型:1.字符串 2.xml
var responseText = xmlHttp.responseText;
alert(responseText);
}else if(xmlHttp.readyState == 4 && xmlHttp.status == 500){
alert("服务器内部异常");
}
};
responseText :服务器的响应字符串。
responseText属性也是XMLHttpRequest的属性,它是用于描述封装服务器给客户端响应的文本数据。在onreadystatechange函数体中可以通过responseText获取通过ajax请求响应到的数据。
3)open(method,url, asynch)方法
其中method表示HTTP请求方式,一般使用"GET","POST"
url表示调用的服务器的地址,就是servlet
asynch表示是否采用异步方式,true表示异步,一般这个参数不写,默认是true,异步,false表示同步。
范例代码
xmlHttp.open("GET", "url?name=xxx&pwd=xxx");
xmlHttp.open("POST", "url");
4)send()方法
客户端向服务器提交数据
1、get方式发送数据
// 参数已经在url上
xmlHttp.open("GET","url?key=value");
var username="zhangsan";
var password="123";
xmlHttp.open("GET","/ajax/helloworld?name="+username+"&password="+password);
xmlHttp.send();
2、post方式发送数据
// 不需要写参数
xmlHttp.open("POST","url");
// post发送参数前,需要设置编码格式
//使用 setRequestHeader() 来添加 HTTP 头
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
xmlHttp.send("name=xxx&pwd=xxx"); // 发送post数据
var username="lisi";
var password="456";
xmlHttp.open("post", "/ajax2/helloworld");
//post方式发送前需要设置编码
xmlHttp.setRequestHeader("CONTENT-TYPE","application/x-www-form-urlencoded");
xmlHttp.send("name="+username+"&password="+password);
【Ajax原生的POST请求】
【ajaxPostDemo.html】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajaxPost请求</title>
</head>
<body>
<button id="btn">发送post请求</button>
</body>
<script>
document.getElementById("btn").onclick = function () {
//ajax发送post请求
//1.创建xhr对象
var xhr = new XMLHttpRequest();
//2.设置监听 请求和响应
xhr.onreadystatechange = function () {
//
if(xhr.readyState == 4 && xhr.status == 200) {
var responseText = xhr.responseText;
//dom操作 局部更新页面
alert(responseText);
}
};
//3.设置请求参数
xhr.open("POST", "/ajaxPostServlet", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//4.发送请求 send发送post请求的数据
xhr.send("name=张三&age=13");
}
</script>
</html>
【AjaxPostServlet.java】
@WebServlet(urlPatterns = "/ajaxPostServlet")
public class AjaxPostServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//处理响应乱码
response.setContentType("text/html;charset=utf-8");
//接收请求数据
String name = request.getParameter("name");
String age = request.getParameter("age");
//模拟异常
// int i=1/0;
//输出
System.out.println("name="+name+",age="+age);
//响应数据
response.getWriter().print("请求已经收到");
}
}