Ajax

  • (一)、Ajax简介
    • 1.什么是Ajax
    • 2.jQuery.ajax介绍
  • (二)、环境搭建
    • 1.创建Model并添加web框架
    • 2.配置Artifacts的lib文件
    • 3.配置web框架下的web.xml
    • 4.配置spring-mvc.xml配置文件
    • 5.配置汇总文件applicationContexe.xml
    • 6.进行测试
  • (三)、伪造Ajax
    • 1.iframe内敛框架伪造Ajax
  • (四)、使用真正的Ajax
    • 1.下载JQuery库
    • 2.导入JQuery静态资源
    • 3.jQuery.ajax的部分参数
    • 4.前端页面布置
    • 5.后端页面布置
  • (五)、Ajax初步体验
    • 1.常规数据展示布局(后端=》前端)
    • 2.用户账户密码验证布局(前端=》后端=》前端)

(一)、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.xsdhttp://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://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选择器进行获取文本框中的值信息,真正传值的是 键 namedata:{"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: 22612Date: 2023/1/2Time: 10:35To 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: 22612Date: 2023/1/2Time: 12:02To 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;}
}

83.【JQuery.Ajax】相关推荐

  1. 【jquery ajax】实现文件上传提交

    ✍️ 作者简介: 前端新手学习中.

  2. 【jquery Ajax 】art-template(ejs)模板引擎的概念与使用

    ✍️ 作者简介: 前端新手学习中.

  3. 20个强大的jQuery翻书插件【 jQuery flipbook】

    ​ 许多网站使用jQuery翻书插件来展示产品目录和销售广告册子.jQuery翻页书解决方案给访客提供了方便而有效的浏览一套东西的体验.如果做得好,就如同手头有一本印刷版的册子.通过翻页书插件,你可以 ...

  4. 【jQuery插件】用jQuery Masonry快速构建一个pinterest网站布局(转)

    [jQuery插件]用jQuery Masonry快速构建一个pinterest网站布局 时间:2011年03月21日作者:愚人码头查看次数:29,744 views评论次数:25条评论 前段时间领导 ...

  5. 【jQuery学习】—实现弹幕效果

    [jQuery学习]-实现弹幕效果

  6. 【jQuery学习】—jQuery对象的访问

    [jQuery学习]-jQuery对象的访问 一.each方法 作用:遍历jQuery对象中的元素 格式:jQuery对象.each(function(index, ele){}); 注意:index ...

  7. 【jQuery学习】—jQuery操作CSS和表格

    [jQuery学习]-jQuery操作CSS和表格 一.jQuery操作CSS 二.jQuery操作表格

  8. 【jQuery学习】—jQuery操作元素位置

    [jQuery学习]-jQuery操作元素位置 一.position方法 作用:返回相对某个元素的偏移量 格式:元素.position() 返回值包含top属性和left属性的对象 如果祖先元素中没有 ...

  9. 【jQuery学习】—jQuery对象的串联

    [jQuery学习]-jQuery对象的串联 一.add方法 作用:把表达式匹配的元素添加到jQuery中 格式:jQuery对象.add(表达式); 二.contents方法 作用:查找匹配元素内部 ...

最新文章

  1. java patterncompiler_PatternCompiler是干什么用的?
  2. 微服务四大网关性能对比
  3. P3项目轶事之一票否决的新员工培训
  4. statsmodels 笔记:seasonal_decompose 时间序列分解
  5. Linux /usr/bin与/usr/local/bin区别
  6. python从零基础到项目实战 当当_Python 3.x网络爬虫从零基础到项目实战
  7. zzuli 2520: 大小接近的点对
  8. 最常用的动态sql语句梳理Mybatis(转)
  9. 信息学奥赛C++语言:哥德巴赫猜想
  10. 【kafka】kafka jmx docker 容器下 跨容器连接 没有到主机的路由 host unreachable
  11. Vue过渡 动画---vue工作笔记0014
  12. java基本数据类型填空题_java基本数据类型练习题
  13. Windows 添加用户
  14. Request.GetOwinContext()打不到
  15. 数据分析第二章课后习题解答
  16. 就叫2021年度总结吧
  17. Vue基础知识总结 11:前端路由vue-router
  18. arcengine cliasic code(转)基于ArcGIS Engine + C#实现用户自定义动态电力符号
  19. 2019.9.6HTML5学习心得02
  20. 认识PV、UV、UV价值

热门文章

  1. SQL解决Error converting data type nvarchar to numeric.
  2. 关于页面自动提交两次的问题(360浏览器)
  3. 股权分配有什么风险?
  4. 离散数学对学计算机有什么用
  5. matlab符号计算证明sin,matlab的符号计算
  6. Java读取Excel,03版本和07版本
  7. GPRS模块中AT指令发送短信的PDU编码规则
  8. 商品服务 - 销售属性维护,属性分组与属性关联
  9. 2022年全球市场旋转压片机总体规模、主要生产商、主要地区、产品和应用细分研究报告
  10. Python拼接图片