83.【JQuery.Ajax】

(一)、Ajax简介

AJAX 是开发者的梦想,因为您能够:

  • 不刷新页面更新网页
  • 在页面加载后从服务器请求数据
  • 在页面加载后从服务器接收数据
  • 在后台向服务器发送数据
  • 异步无刷新页面
    比如我们经常用的百度,我们对其输入一个a的时候。他会在不刷新页面的前提下进行更新网页,弹出了下面的提示信息

在这里插入图片描述

1.什么是Ajax

Ajax是Asynchronous JavaScript and XML的缩写这一技术能够向服务器请求额外的数据而无需卸载整个页面,会带来良好的用户体验。传统的HTTP请求流程大概是这样的,浏览器向服务器发送请求-〉服务器根据浏览器传来数据生成response-〉服务器把response返回给浏览器-〉浏览器刷新整个页面显示最新数据,这个过程是同步的,顺序执行。

AJAX 在浏览器与 Web 服务器之间使用异步数据传输(HTTP 请求)从服务器获取数据,这里的异步是指脱离当前浏览器页面的请求、加载等单独执行,这意味着可以在不重新加载整个网页的情况下,通过JavaScript接受服务器传来的数据,然后操作DOM将新数据对网页的某部分进行更新,使用Ajax最直观的’感受是向服务器获取新数据不需要刷新页面等待了。这个过程是异步的。

2.jQuery.ajax介绍

  • 纯JS原生实现Ajax我们不去说了,这里我们直接使用jQuery提供的。避免重复造轮子,有兴趣的话可以去了解JS原生XMLHttpRequest.
  • Ajax的核心是XMLHttpRequest对象(XHR).XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取数据
  • jQuery 提供了多个与AJAX有关的方法
  • 通过jQuery AJAX方法,我们能够使用HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或JSON -同时我们能够把这些外部数据直接载入网页的被选元素中
  • jQuery 不是生产者而是大自然的搬运工
  • jQuery Ajax本质就是XMLHttpRequest, 对他进行了封装,方便调用!

(二)、环境搭建

1.创建Model并添加web框架

在这里插入图片描述

2.配置Artifacts的lib文件

在这里插入图片描述

3.配置web框架下的web.xml

这里前端控制器的文件路径指向的是ApplicationContext.xml总的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--    配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:ApplicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!--  配置字符集乱码  -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

4.配置spring-mvc.xml配置文件

四个操作: 一是注解驱动 二是静态资源过滤 三是注解扫描 四是视图解析器

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/mvc  
       http://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/context  
       http://www.springframework.org/schema/context/spring-context.xsd
">
<!--  1.注解驱动-->
    <mvc:annotation-driven/>
<!--  2.静态资源处理器  -->
    <mvc:default-servlet-handler/>
<!--  3.注解扫描  -->
    <context:component-scan base-package="com.jsxs.controller"/>
<!--  4.视图解析器  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

5.配置汇总文件applicationContexe.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--   导入controller的配置文件 -->
    <import resource="classpath:spring-mvc.xml"/>
</beans>

6.进行测试

利用JSON进行测试,因为@RestController可以不走视图解析器,直接走数据跳转了

package com.jsxs.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AjaxController {
    
    
    @RequestMapping("/t1")
    public String test(){
    
    
        return "hello";
    }
}

在这里插入图片描述

(三)、伪造Ajax

1.iframe内敛框架伪造Ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>iframe测试页面无刷新</title>
  <script>
    function go(){
      
      
      // 所有的值变量,提前获取,也就是先获取变量后面进行赋值。
      var url=document.getElementById("url").value;
      // 把获取到的url的值给提交按钮
      // document.getElementById("iframe1").src="https://blog.csdn.net/qq_69683957/article/details/128425999";
      document.getElementById("iframe1").src=url;
    }
  </script>
</head>
<body>
<div>
  <p>请输入需要访问的地址:</p>
  <p>
    <input type="text" id="url">
<!--    给按钮绑定一个事件-->
    <input type="button" value="提交" onclick="go()">
  </p>
</div>
<div>
  <iframe id="iframe1" style="width: 100%;height: 500px"></iframe>
</div>
</body>
</html>

在这里插入图片描述

在这里插入图片描述

(四)、使用真正的Ajax

https://jquery.com/

1.下载JQuery库

在这里插入图片描述

2.导入JQuery静态资源

在这里插入图片描述

3.jQuery.ajax的部分参数

jQuery.ajax(...)
      部分参数:
            url:请求地址
            type:请求方式,GETPOST1.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 将自动替换 ? 为正确的函数名,以执行回调函数

在文本框中,如果想要获取前端的值,我们的属性应该设置成name属性,并不是id属性

4.前端页面布置

index.jsp
我们设置一个输入框,设置id为username。以及失去焦点事件onblur。当我们失去焦点得时候我们会经过js的一个方法。这个方法我们用ajax来进行操作,url 路径 data 数据 callback : 后端返回什么数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
<%--    导入 juequery--%>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.1.js"></script>
    <script>
        function a(){
      
      
            <%--   $.  符号相当于 jQuery. ,前者是后者的简写   --%>
            $.post({
      
      
                url:"${pageContext.request.contextPath}/a1",
                //********真正的和后端匹配的属性应该是name属性,而不是id属性。在这里我们只是
                // 通过id选择器进行获取文本框中的值信息,真正传值的是 键 name
                data:{
      
      "name":$("#username").val()},
                success:function (data){
      
      
                    alert(data);
                }
            })
        }

    </script>
  </head>
  <body>
<%--  失去焦点的时候,发起一个请求到后端--%>
  <input type="text" id="username" onblur="a()">
  </body>
</html>

5.后端页面布置

package com.jsxs.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AjaxController {
    
    
    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
    
    
        if ("JSXS".equals(name)){
    
    
            response.getWriter().write("true");
        }else {
    
    
            response.getWriter().write("false");
        }
    }
}

在这里插入图片描述

在这里插入图片描述

(五)、Ajax初步体验

1.常规数据展示布局(后端=》前端)

我们首先设置一个按钮框,并设置id标签。我们通过js对这个按钮进行监听,假如说点击了这个按钮我们就使用ajax进行获取后端传递过来的JSON值。
test2.jsp
这里的data值就是我们后端通过JSON传递进来的,所以我们可以直接使用。

<%--
  Created by IntelliJ IDEA.
  User: 22612
  Date: 2023/1/2
  Time: 10:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="static/js/jquery-3.6.1.js"></script>
    <script>
        $(function () {
      
      
            $("#btn").click(function () {
      
      
                //&.post(url , param[可省略] ,success)
                // 回调函数顾名思义: 把数据传回到前端,也就是后端响应的数据
                $.post("${pageContext.request.contextPath}/a2",function (data){
      
      
                    console.log(data);
                    var html="";
                    for (let i = 0; i < data.length; i++) {
      
      
                        html +="<tr>"+
                            "<td>"+data[i].name+"</td>"+
                            "<td>"+data[i].age+"</td>"+
                            "<td>"+data[i].sex+"</td>"+
                            "<tr>"
                    }
                    $("#context").html(html)
                });

            })
        });

    </script>
</head>
<input type="button" value="加载数据" id="btn">
<body>
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <tbody id="context">

    </tbody>
</table>
</body>
</html>

这里我们负责传递JSON值,因为我们不经过视图解析器所以我们这里直接传递的是一个JSON值

package com.jsxs.controller;

import com.jsxs.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

    @RequestMapping("/a2")
    public List<User> a2(){
    
    
        ArrayList<User> users = new ArrayList<>();
//        添加数据
        users.add(new User("吉士先生1",15,"娜娜"));
        users.add(new User("吉士先生2",15,"娜娜"));
        users.add(new User("吉士先生3",15,"娜娜"));
        return users;
    }
}

在这里插入图片描述

2.用户账户密码验证布局(前端=》后端=》前端)

ajax: 用户体验,我们设置两个基本的输入框,然后通过ajax进行获取前端传进来的数据,然后通过success回滚即可。如何展示数据呢,我们只需要对其进行

<%--
  Created by IntelliJ IDEA.
  User: 22612
  Date: 2023/1/2
  Time: 12:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="static/js/jquery-3.6.1.js"></script>
    <script>
        function a1(){
      
      
            $.post({
      
      
                url: "${pageContext.request.contextPath}/a3",
                data:{
      
      "name":$("#name").val()},
                success:function (data){
      
      
                    //  因为传入过来的是一个JSON对象,我们要对其进行数据转换
                    if (data.toString()==='OK'){
      
      
                        $("#userInfo").css("color","green");

                    }else {
      
      
                        $("#userInfo").css("color","red");
                    }console.log(data);
                    $("#userInfo").html(data)
                }
            })
        }
        function a2(){
      
      
            $.post({
      
      
                url: "${pageContext.request.contextPath}/a3",
                data:{
      
      "pwd":$("#password").val()},
                success:function (data){
      
      
                    //  因为传入过来的是一个JSON对象,我们要对其进行数据转换
                    if (data.toString()==='OK'){
      
      
                        $("#pwdInfo").css("color","green");

                    }else {
      
      
                        $("#pwdInfo").css("color","red");
                    }console.log(data);
                    $("#pwdInfo").html(data)
                }
            })
        }
    </script>
</head>
<body>
<p>
    用户名 : <input type="text" id="name" onblur="a1()">
    <span id="userInfo"></span>
</p>
<p>
    密码 : <input type="text" id="password" onblur="a2()">
    <span id="pwdInfo"></span>
</p>
</body>
</html>

进行获取数据,并且进行返回JSON,JSON是一个JSON对象,我们要进行字符串转换。

package com.jsxs.controller;

import com.jsxs.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController {
    
    
    @RequestMapping("/a3")
    public String a3(String name,String pwd){
    
    
        String msg="";
        System.out.println(name);
        System.out.println(pwd);
        if (name!=null){
    
    
            if ("吉士先生".equals(name)){
    
    
                msg="OK";
            }else {
    
    
                msg="Error";
            }
        }
        if (pwd!=null){
    
    
            if ("121788".equals(pwd)){
    
    
                msg="OK";
            }else {
    
    
                msg="Error";
            }
        }
        return msg;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_69683957/article/details/128514541