Ajax入门

AJAX

一、简介

AJAX = Asynchronous JavaScript and XML (异步的JavaScript和XML)。

Ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术

Ajax不是一门语言,而是一门技术。

传统的网页想要更新内容或者提交表单都需要重新加载整个网页

利用Ajax可以做:

  • 注册时,输入用户名自动检测用户是否已经存在
  • 登录时,提示用户密码错误
  • 删除数据时,将ID发送到后台,进行删除
  • ...etc

伪造Ajax

我们可以使用前端的一个标签来伪造一个ajax的样子。iframe标签

主要熟悉一下JS

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>FakeAjax</title>
</head>
<body>

<script type="text/javascript">
    window.onload = function (){
        let date = new Date();
        document.getElementById("currentTime").innerText=date.toLocaleDateString()+date.toLocaleTimeString();
    }
    function fun(){
        let value = document.getElementById("url").value;
        console.log(value);
        document.getElementById("iframePosition").src = value;
    }
</script>

<div>
    <span>现在的时间为:</span>
    <span id = "currentTime"></span>
    <p>请输入要加载的地址:</p>
    <p>
        <input type="text" id = "url" value = "https://www.baidu.com"/>
        <input type="button" value="提交" onclick="fun()"/>
    </p>
</div>

<div>
    <h3>加载页面位置:</h3>
    <iframe id="iframePosition" style="width: 100%;height: 400px"></iframe>
</div>
</body>
</html>

二、Jquery.ajax

Ajax的核心是XMLHttpRequest对象(XHR)。

通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON – 同时您能够把这些外部数据直接载入网页的被选元素中。

jQuery 不是生产者,而是大自然搬运工。

jQuery Ajax本质就是 XMLHttpRequest,对他进行了封装,方便调用!

jQuery.ajax(...)
      部分参数:
            url:请求地址
            type:请求方式,GET、POST(1.9.0之后用method)
        headers:请求头
            data:要发送的数据
    contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
          async:是否异步
        timeout:设置请求超时时间(毫秒)
      beforeSend:发送请求前执行的函数(全局)
        complete:完成之后执行的回调函数(全局)
        success:成功之后执行的回调函数(全局)
          error:失败之后执行的回调函数(全局)
        accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
        dataType:将服务器端返回的数据转换成指定类型
          "xml": 将服务器端返回的内容转换成xml格式
          "text": 将服务器端返回的内容转换成普通文本格式
          "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
        "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
          "json": 将服务器端返回的内容转换成相应的JavaScript对象
        "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

场景一:失去焦点,发起ajax请求,后台返回结果给前台

前台代码:index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
    <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        function fun(){
            $.ajax({
                url:"${pageContext.request.contextPath}/ajax/a1",
                data:{"name":$("#textName").val()}, // 以用Json传到后台
                success:function (data,status){  // 这个data时后台返回的数据
                    console.log(data);
                    console.log(status);
                }
            });
        }
    </script>
</head>
<body>

<%--onblur:失去焦点触发事件--%>
用户名:<input type="text" id="textName" onblur="fun()"/>
</body>
</html>

注意:

success:function (data,status){  // 这个data时后台返回的数据
    console.log(data);
    console.log(status);
}

这个data是后台传给前端的数据,为JSON格式

利用Servlet处理ajax 的URL地址

public class AjaxTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        if ("admin".equals(name)){
            resp.getWriter().write("true");
        }else {
            resp.getWriter().write("false");
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
  1. 注册web.xml
    <servlet>
        <servlet-name>ajax</servlet-name>
        <servlet-class>com.hujesse.servlet.AjaxTest</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ajax</servlet-name>
        <url-pattern>/ajax/a1</url-pattern>
    </servlet-mapping>

测试效果:

场景二:利用ajax查询数据:

后端还是使用Servlet,但是我返回的Json格式似乎还有问题,不能展示格式

public class AjaxTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<AjaxUser> userList = new ArrayList<AjaxUser>();
        userList.add(new AjaxUser("hujesse4",20,"man"));
        userList.add(new AjaxUser("hujesse83",21,"man"));
        Gson gson = new Gson();
        String s=  gson.toJson(userList);
        resp.getWriter().write(s);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

前台代码稍微麻烦一点 ....

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <tbody id="content">
    </tbody>
</table>

<script src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
<script>

    $(function () {
        $("#btn").click(function () {
            $.post("${pageContext.request.contextPath}/ajax/a1",function (data) {
                console.log(data)
                let data2 = JSON.parse(data);
                console.log(data2)
                var html="";
                for (var i = 0; i <data2.length ; i++) {
                    html+= "<tr>" +
                        "<td>" + data2[i].name + "</td>" +
                        "<td>" + data2[i].age + "</td>" +
                        "<td>" + data2[i].sex + "</td>" +
                        "</tr>"
                }
                $("#content").html(html);
            });
        })
    })
</script>
</body>
</html>

注意最重要的是将Json字符串转换为Json对象

let data2 = $.parseJSON( data ); 这个是Jquery的写法

JSON.parse(str)。str为json字符串 普通是这样写

.. 之后注册Servlet

场景三:登录场景,输入框后面的提示,利用ajax做验证

前端代码如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>ajax</title>
    <script src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
    <script>

        function a1(){
            $.ajax({
                url:"${pageContext.request.contextPath}/a3",
                data:{'name':$("#name").val()},
                success:function (data) {
                    if (data.toString()=='ok'){
                        $("#userInfo").css("color","green");
                    }else {
                        $("#userInfo").css("color","red");
                    }
                    $("#userInfo").html(data);
                }
            });
        }
        function a2(){
            $.ajax("${pageContext.request.contextPath}/a3", {'pwd':$("#pwd").val()}, function (data) {
                    if (data.toString()=='ok'){
                        $("#pwdInfo").css("color","green");
                    }else {
                        $("#pwdInfo").css("color","red");
                    }
                    $("#pwdInfo").html(data);
                }
            );
        }

    </script>
</head>
<body>
<p>
    用户名:<input type="text" id="name" onblur="a1()"/>
    <span id="userInfo"></span>
</p>
<p>
    密码:<input type="text" id="pwd"  onblur="a2()"/>
    <span id="pwdInfo"></span>
</p>
</body>
</html>

后端代码为:

public class AjaxTest2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String msg = "";
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        if (name!=null ){
            if ("admin".equals(name)){
                msg = "ok";
            }else {
                msg="用户名有误";
            }
        }
        if (pwd!=null ){
            if ("admin".equals(pwd)){
                msg = "ok";
            }else {
                msg="密码输入有误";
            }
        }
        resp.getWriter().write(msg);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

注册xml

    <servlet>
        <servlet-name>ajax2</servlet-name>
        <servlet-class>com.hujesse.servlet.AjaxTest2</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ajax2</servlet-name>
        <url-pattern>/a3</url-pattern>
    </servlet-mapping>

三、总结

使用Jquery需要导入jquery,使用vue就导入vue。封装了原生的代码

三部曲:

  • 1.编写对应处理的Controller,返回消息或者字符串或者Json格式的数据
  • 2.编写ajax请求
    • 2.1 url:Controller请求
    • 2.2:data:key/v 键值对 传给后端
    • 2.3:success回调函数
  • 3.给ajax绑定事件,”点击“, “失去焦点” ,”键盘弹起“

前端ajax是如何把值传给后端servlet(Controller)的呢?

这里前端代码为

<script>
        function fun(){
            $.ajax({
                url:"${pageContext.request.contextPath}/ajax/a1",
                data:{"name":$("#textName").val()}, // 以用Json传到后台
</script>
</head>
<body>

<%--onblur:失去焦点触发事件--%>
用户名:<input type="text" id="textName" onblur="fun()"/>

这里是用的data封装的key/value键值对得到的

下面给出二种得到data中参数的值的方法

  • 1.原生Servlet
String name = req.getParameter("name");
  • 2.Spring
@RequestMapping("/a3")
public String ajax3(String name,String pwd){

就能直接获得前端传来的值

json字符串如何转为对象

let data2 = $.parseJSON( data ); 这个是Jquery的写法

JSON.parse(str)。str为json字符串 普通是这样写

狂神说Java之Ajax 视频网站:https://www.bilibili.com/video/BV1Kt411u7BV/?spm_id_from=333.788.recommend_more_video.-1
狂神说Java微信笔记:https://mp.weixin.qq.com/s/tB4YX4H59wYS6rxaO3K2_g
真的很感谢狂神,真的

posted @ 2021-03-30 12:14  能借我十块钱吗  阅读(67)  评论(0编辑  收藏  举报