json
Ajax
AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的 网页开发技术。
ajax 是一种浏览器异步发起请求。局部更新页面的技术。
javaScript 原生 Ajax 请求
原生的 Ajax 请求,
1、我们首先要创建 XMLHttpRequest 对象
2、调用 open 方法设置请求参数
3、调用 send 方法发送请求
4、在 send 方法前绑定 onreadystatechange 事件,处理请求完成后的操作。
创建一个 html 页面,发起请求。代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="pragma" content="no-cache" /><meta http-equiv="cache-control" content="no-cache" /><meta http-equiv="Expires" content="0" /><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title><script type="text/javascript">function ajaxRequest() {// 1、我们首先要创建XMLHttpRequestxmlhttpprequest = new XMLHttpRequest();// 2、调用open方法设置请求参数xmlhttpprequest.open("GET","http://localhost:8080/Cookie_session/ajaxServlet?action=javaScriptAjax",true);// 4、在send方法前绑定onreadystatechange事件,处理请求完成后的操作.xmlhttpprequest.onreadystatechange = function (){if (xmlhttpprequest.readyState == 4&&xmlhttpprequest.status == 200){jsonObj = JSON.parse(xmlhttpprequest.responseText);//把响应的数据显示在页面上document.getElementById("div01").innerHTML = "编号" + jsonObj.id+",姓名"+jsonObj.name;// document.getElementById("div01").innerHTML = xmlhttpprequest.responseText;}}// 3、调用send方法发送请求xmlhttpprequest.send();}</script></head><body><button onclick="ajaxRequest()">ajax request</button><div id="div01"></div></body></html>
创建一个 AjaxServlet 程序接收请求
package servlet;import com.google.gson.Gson;import pojo.Person;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class AjaxServlet extends BaseServlet{protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {System.out.println("请求过来了");Person person = new Person(1,"肖战");//转为json格式的字符串Gson gson = new Gson();String personJsonString = gson.toJson(person);resp.getWriter().write(personJsonString);}}
xmlhttpprequest.open(“GET”,”http://localhost:8080/Cookie_session/ajaxServlet?action=javaScriptAjax",true);
该处为true时,表示是异步请求,为false时,表示为同步请求
同步请求:就是要等前面的执行结束之后再执行,只有一个线程
异步请求:同时进行,多线程进行,不用等待,推荐使用
