JS实现AJAX完整Demo

1.请求类型为POST

post.jsp

<%--
  Created by IntelliJ IDEA.
  User: 杨帆
  Date: 2019/10/17
  Time: 11:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        function onclickAjax() {
//            第一步:创建XMLHttpRequest对象
            var xhr = null;
            if(window.XMLHttpRequest){
                // 兼容 IE7+, Firefox, Chrome, Opera, Safari
                xhr = new XMLHttpRequest();
            }else{
                //兼容 IE6, IE5
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            }
//            第二步:设置请求方式
            xhr.open("POST","ajaxPost",true);
//            第三步:发送请求
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send("name=yangfan&password=123");
//            第四步:设置回调函数
            xhr.onreadystatechange = function () {
                if(xhr.readyState==4 &&xhr.status==200){
                    document.getElementById("test").innerHTML = xhr.responseText;
                }
            }
        }
    </script>
</head>
<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="test"></div>
</body>
</html>

服务器端的代码:

@RequestMapping("ajaxPost")
    public void ajaxPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        String str = "Post";
        response.getWriter().write(str);
    }

进行测试:
在这里插入图片描述
点击测试
在这里插入图片描述
控制台:

yangfan
123

2.请求类型为Get时

get.jsp

<%--
  Created by IntelliJ IDEA.
  User: 杨帆
  Date: 2019/10/17
  Time: 11:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script>
        function onclickAjax() {
            var xhr = null;
            if(window.XMLHttpRequest){
                // 兼容 IE7+, Firefox, Chrome, Opera, Safari
                xhr = new XMLHttpRequest();
            }else{
                //兼容 IE6, IE5
                xhr = new ActiveXObject("Microsoft.XMLHTTP")
            }
//            第二步:设置请求方式
            xhr.open("GET","ajaxGet?name=yangfan&password=123",true);
//            第三步:发送请求
            xhr.send();
//            第四步:设置回调函数
            xhr.onreadystatechange = function () {
                if(xhr.readyState==4 &&xhr.status==200){
                    document.getElementById("test").innerHTML = xhr.responseText;
                }
            }
        }
    </script>
</head>
<body>
<input type="button" value="测试" onclick="onclickAjax()">
<div id="test"></div>
</body>
</html>

服务器端的代码:

@RequestMapping("ajaxGet")
    public void ajaxGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        String str = "Get";
        response.getWriter().write(str);
    }

进行测试:
在这里插入图片描述
点击测试

在这里插入图片描述
控制台:

yangfan
123

3.参考博客

Ajax原理
快速掌握Ajax

4.补充JQuery实现AJAX

<%--
  Created by IntelliJ IDEA.
  User: 杨帆
  Date: 2019/10/17
  Time: 11:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Jpost</title>
    <script src="js/jquery.min (1).js"></script>
    <script>
        $(function(){
            $("#haha").click(function(){
                $.ajax({
                    type:"POST",
                    url:"ajaxPost",
                    data:"name=yangfan&password=123",
                    success:function (msg) {
                        alert(typeof msg );
                        $("#test").html(msg);
                    }
                });
            });
        });
    </script>
</head>
<body>
<input id="haha" type="button" value="测试">
<div id="test"></div>
</body>
</html>

效果和上面的js实现一样,当请求类型为GET时,只需要将type:“POST”,改为type:"GET"即可

5 AJAX与json的运用

今天下午看了一下ajax与json,说说自己的理解。

1.首先json是对象表示法(JavaScript Object Notation) 是一种存储数据的方式。在js中我们可以通过对象.属性名的形式取出json中的值,这样十分方便我们取值。

2.在ajax中如果我们从后台传过来的数据类型可以转化成json,那么前后端的数据传递将会变得十分方便。

举例:
test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 杨帆
  Date: 2019/10/17
  Time: 15:52
  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="js/jquery.min%20(1).js"></script>
    <script>
        $(function(){
            $("#but").click(function(){
                $.ajax({
                    type:"POST",
                    url:"test",
                    data:"name=haha&password=123",
                    dataType:"json",
                    success:function (msg) {
                        alert(typeof msg);
                        alert(msg);
                        $("#test").append(msg.name);
                        $("#test").append(msg.password);
                        $("#test").append(msg.age);
                    },
                    error:function(){
                        alert("系统错误!");
                    }
                });
            });
        });
    </script>
</head>
<body>
<button id="but">测试</button>
<div id="test"></div>
</body>
</html>

后台代码:

@RequestMapping("test")
    public void test1(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        System.out.println(name);
        System.out.println(password);
        Map<String,Object> map = new HashMap<>();
        map.put("name","tht");
        map.put("password",520);
        map.put("age",20);
        Gson gson = new Gson();
        String str = gson.toJson(map);
        System.out.println(str);
        response.getWriter().write(str);
    }

我这里使用了Google的Gson将map转化成json的字符串形式,传递给前端。然后我们只需要在前端将字符串形式的json数据转化成json即可。dataType:"json"帮我们做到了这一点。如果不使用这个属性,你可以这样来转化

var json = JSON.parse(msg);

之后,在js中我们就可以使用对象.属性来取出服务器传过来的所有数据,很方便!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值