SSM_Ajax

SSM_Ajax

1、使用html伪造一个ajax

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    window.onload = function(){
        //时间戳
        var myDate = new Date();
        document.getElementById('currentTime').innerText = myDate.getTime();
    };
    function go() {
        var targetUrl=document.getElementById("url").value;
        console.log(targetUrl);
        document.getElementById("iframePosition").src = targetUrl;
    }
</script>


<div>
    <p>请输入要加载的网站<span id="currentTime"></span></p>
    <p>
        <input type="text" value="www.baidu.com" id="url"/>
        <input type="button" value="提交" onclick="go()">
    </p>
</div>
<div>
    <h3>加载页面位置</h3>
    <iframe id="iframePosition" style="width: 100%;height: 500px"></iframe>
</div>

</body>
</html>

2、使用JQuery的ajax

onblur(失去焦点)

导入头部文件:

script标签不能自闭和,不然会出错,写完alt+回车下载。

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>

这里直接使用jquery提供的,方便学习和使用,可以上网了解下JS原生XMLHttpRequest !

Ajax的核心是XMLHttpRequest对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。

jQuery 提供多个与 AJAX 有关的方法。

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

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 将自动替换 ? 为正确的函数名,以执行回调函数
jQuery.get(url, [data], [callback], [type])

2.1 一个简单的ajax验证

后端:

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

前端:使用post提交

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script>
      function a1() {
        $.post({
          url:"${pageContext.request.contextPath}/a1",
          data:{"name":$("#userName").val()},
          success:function (data,status) {
              console.log(data);
              console.log(status);
          },
          error:function () {
              alert("请求出错");
          }
        });
      }
    </script>
  </head>
  <body>
  <%--onblur:失去焦点触发事件--%>
  用户名:<input type="text" id="userName" οnblur="a1()"/>
  </body>
</html>

2.2 通过ajax获得后端的数据

@RequestMapping("/a2")
public List<User> ajax2() throws IOException {
    List<User> userList=new ArrayList<User>();

    userList.add(new User("小厮1",20,"男"));
    userList.add(new User("小厮2",20,"男"));
    userList.add(new User("小厮3",20,"男"));

    return userList;
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                $.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>"
                    }
                    $("#content").html(html);
                });
            })
        })
    </script>
</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>
</body>
</html>

2.3 一个登录验证

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script>
        function aa1() {
            $.post({
                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 aa2() {
            $.post({
                url:"${pageContext.request.contextPath}/a3",
                data:{'pwd':$("#pwd").val()},
                success:function (data) {
                    if(data.toString()==="ok"){
                        $("#pwdInfo").css("color","green");
                    }else{
                        $("#pwdInfo").css("color","red");
                    }
                    $("#pwdInfo").html(data);
                }
            });
        }
    </script>
</head>
<body>

<div>
    <p>
        账号:<input type="text" id="name" οnblur="aa1()">
        <span id="userInfo"></span>
    </p>
    <p>
        密码:<input type="password" id="pwd" οnblur="aa2()">
        <span id="pwdInfo"></span>
    </p>
</div>


</body>
</html>
@RequestMapping("/a3")
public String ajax3(String name,String pwd) throws IOException {
    String msg="";

    if(name!=null){
        if(name.equals("xiaosi")){
            msg="ok";
        }else{
            msg="用户名错误";
        }
    }
    if(pwd!=null){
        if(pwd.equals("123456")){
            msg="ok";
        }else{
            msg="密码错误";
        }
    }
    return msg;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值