AJAX

it2025-09-07  9

Ajax的实现方式

原生js实现步骤 Jquery实现方式

原生js实现

步骤

1:判断浏览器引擎对象 2:建立连接 3:发送请求 4:接收并处理来自服务器的响应结果 HTML页面代码: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax 原生js实现方式</title> <script> function fun() { //1.判断浏览器引擎对象 var xmlhttp; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //2.建立连接 true(异步,默认) false(同步) xmlhttp.open(请求方式,请求url,异步/同步) xmlhttp.open("GET","ajaxServlet?uname=jack",true); //3.发送请求 xmlhttp.send(); //4.接收并处理来自服务器的响应结果 xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ //获取服务器的响应文本 var v = xmlhttp.responseText; alert(v); } } } </script> </head> <body> <button value="使用原生js请求数据" onclick="fun()">使用原生js请求数据</button> </body> </html>

AjaxServlet:

@WebServlet("/ajaxServlet") public class AjaxServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;utf-8"); req.setCharacterEncoding("UTF-8"); String name = req.getParameter("uname"); resp.getWriter().println("hello "+name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }

Jquery实现方式

最新回复(0)