Ajax(Asychronous JavaScript and XML)笔记
Posted jepson6669
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax(Asychronous JavaScript and XML)笔记相关的知识,希望对你有一定的参考价值。
1 Ajax简介
1 ajax概念
2 什么是同步?什么是异步?
3 ajax原理
2 javascript原生的ajax
1 ajax.html代码
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function fn1(){ //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象 var xmlHttp = new XMLHttpRequest(); //2、绑定监听 ---- 监听服务器是否已经返回相应数据 xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ //5、接受相应数据 var res = xmlHttp.responseText; document.getElementById("span1").innerHTML = res; } } //3、绑定地址 xmlHttp.open("GET","/WEB22/ajaxServlet?name=lisi",true); //4、发送请求 xmlHttp.send(); } function fn2(){ //1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象 var xmlHttp = new XMLHttpRequest(); //2、绑定监听 ---- 监听服务器是否已经返回相应数据 xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ //5、接受相应数据 var res = xmlHttp.responseText; document.getElementById("span2").innerHTML = res; } } //3、绑定地址 xmlHttp.open("POST","/WEB22/ajaxServlet",false); //4、发送请求 xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("name=wangwu"); } </script> </head> <body> <input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1"></span> <br> <input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2"></span> <br> <input type="button" value="测试按钮" onclick="alert()"> </body> </html>
2 AjaxServlet代码
package www.test.ajax01; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.getWriter().write("zhangsan"); /*try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); }*/ String parameter = request.getParameter("name"); response.getWriter().write(Math.random()+parameter); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3 注意事项
4 ajax图解
以上是关于Ajax(Asychronous JavaScript and XML)笔记的主要内容,如果未能解决你的问题,请参考以下文章