什么是ajax
异步的javaScript 和 xml
1、异步和同步:在客户端和服务器互相通信的基础上
同步:客户端必须等待服务器的响应,在等待期间不能做其他操作
异步:客户端不必等待服务器的响应,在期间能做其他操作
2、Ajax是一种无需重新加载整个网页的情况下,可以更新部分网页的技术
jQuery可以通过三种方式进行数据的传值
$.post():jQuery.post(url, [data], [callback], [type])
$.get():jQuery.get(url, [data], [callback], [type])
$.ajax({}):jQuery.ajax(url,[settings])
属性:
ur:待载入页面的URL地址
data:待发送 Key/value 参数
callback:载入成功时回调函数
type:返回内容格式,xml, html, script, json, text, _default
案例
servlet类
package com.xmcc.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/ajaxServlet") public class AjaxServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); System.out.println(username); String age = request.getParameter("age"); System.out.println(age); response.getWriter().write("ssssssss"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response ); } }
jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <script src="js/jquery-3.3.1.min.js"></script> <script> //字符串拼接 function aaa() { //使用ajax提交请求 $.ajax({ url:"/ajaxServlet", data:"username=coco&age=12", type:"POST", success:function (obj) { alert(obj) } }) } //json格式 function bbb() { //使用ajax提交请求 $.ajax({ url:"/ajaxServlet", data:{"username":"coco","age":12}, type:"POST", success:function (obj) { alert(obj) }, error:function () { alert("111111111111") }, //服务器响应的数据格式 dataType:"text" }) } function ccc() { //使用$.get()提交请求 $.get("/ajaxServlet","username=coco",function (obj) { alert(obj) },"text") //使用$.post()提交请求 $.post("/ajaxServlet","username=coco",function (obj) { alert(obj) },"text") } </script> <html> <head> <title>Title</title> </head> <body>
<button id="btn" οnclick="aaa()">点击1</button>
<button id="btn" οnclick="bbb()">点击2</button>
<button id="btn" οnclick="ccc()">点击3</button>
</body>
</html>