jQuery.Ajax


一、了解Ajax

  1. AJAX = Asynchronous JavaScript and XML,AJAX = 异步 JavaScript 和 XML

  2. AJAX 是一种用于创建快速动态网页的技术。

  3. AJAX 通过在后台与服务器进行少量数据交换,使网页实现异步更新。这意味着可以在不重载整个页面的情况下,对网页的某些部分进行更新。

  4. 传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个页面。

二、搭配环境

参考文章:SpringMVC
同时需要引入jQuery的js文件。

三、Ajax:jQuery $.post() 方法

1.了解$.post()方法

$.post() 方法通过 HTTP POST 请求向服务器提交数据。

源码:

jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );

我们可以看到post()方法最终还是调用 ajax方法,对应的参数type=post

使用语法:

$.post({
   url: page,
   data:{"name":value},
   success: function(result){
      $("#checkResult").html(result);
   }
});

2.例子1

例子:
定义一个输入框,它失去焦点的时候,发起一个请求(携带信息)到后台,实现页面的一个局部更新。

  • jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

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

    <script>
      function fun() {
        $.post({
          url:"${pageContext.request.contextPath}/a1",
          data:{"name":$("#serch").val()},
          success:function (data) {
            alert(data);
          }
        })

      }

    </script>

  </head>
  <body>
<%--失去焦点的时候,发起一个请求(携带信息)到后台--%>
  搜索框:<input type="text" id="serch" onblur="fun()">
  </body>
</html>
  • url路径对应controller类
@Controller
public class AjaxController {

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        if ("hello".equals(name)){
            response.getWriter().print("true");
        }else {
            response.getWriter().print("false");
        }
    }
}

在这里插入图片描述

3.例子2:Ajax异步加载数据

  • 后台数据(我们可以把数据转化成json字符串,在传给前端,这里暂时不这样,怎样转json文章指路:JSON交互处理
@Controller
public class AjaxController {

    @RequestMapping("/a2")
    @ResponseBody
    public List<User> user(){
        List<User> users = new ArrayList<>();

        users.add(new User(1001,"小明","abc"));
        users.add(new User(1002,"小军","456"));
        users.add(new User(1003,"晓丽","123"));

        return users;
    }
}
  • jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<input type="button" value="获取数据" onclick="fun2()">
<table width="80%" align="center">
    <tr>
        <td>ID</td>
        <td>用户名</td>
        <td>密码</td>
    </tr>
    <tbody id="content">
    <%--数据从后台拿--%>
    </tbody>

</table>

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    function fun2() {
        $.post({
            url:"${pageContext.request.contextPath}/a2",
            success:function (data) {
                var html="";
                for (let i = 0; i < data.length; i++) {
                    html += "<tr>"+
                        "<td>"+data[i].id+"</td>"+
                        "<td>"+data[i].name+"</td>"+
                        "<td>"+data[i].pwd+"</td>"+
                        "</tr>"
                }
                $("#content").html(html)
            }
        })

    }
</script>

</body>
</html>

不需要刷新总个界面,局部加载
在这里插入图片描述

4.例子3:用户名验证

注册用户时,判断用户是否已存在:

  • 后台数据(实际案例中用户名数据来自数据库,这里暂时固定一个,前端传来的gaolang就返回OK,不然返回用户名已存在)
@Controller
public class AjaxController {

    @RequestMapping("/register")
    @ResponseBody
    public String register(String name){
        String flag = "";
        if (name.equals("gaolang")){
            flag = "OK";
        }else {
            flag = "用户名已存在";
        }

        return flag;
    }

}
  • jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
        function fun3() {
            $.post({
                url:"${pageContext.request.contextPath}/register",
                data:{"name":$("#name").val()},
                success:function (data) {
                    if (data.toString()==='OK'){
                        $("#userInfo").css("color","green");
                    }
                    $("#userInfo").html(data);
                }
            })
        }
    </script>
</head>
<body>
<p>
    用户名:<input type="text" id="name" onblur="fun3()">
    <span id="userInfo"></span>
</p>

</body>
</html>

如果出现乱码的话,在springmvc配置文件中加入:

    <!--JSON乱码问题配置-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

效果图:
在这里插入图片描述

四、小结

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

  1. get和post都是 $.ajax的简化版
    通过源码,可以看出,get和post的用法基本一样, HTTP请求向服务器的方式不同。
jQuery.each( [ "get", "post" ], function( i, method ) {
	jQuery[ method ] = function( url, data, callback, type ) {

		// Shift arguments if data argument was omitted
		if ( isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = undefined;
		}

		// The url can be an options object (which then must have .url)
		return jQuery.ajax( jQuery.extend( {
			url: url,
			type: method,
			dataType: type,
			data: data,
			success: callback
		}, jQuery.isPlainObject( url ) && url ) );
	};
} );
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值