jquery ajax post()


jquery ajax post()

 

应用:使用post发送异步请求,从后端获取数据

 

 

*********************

语法:post(url,[data],[callback])

 

url:请求获取数据地址

data:可选,传递给后端的数据

 

callback:可选,请求成功后调用,请求失败不会调用,函数参数:

response:请求结果

status:请求结果状态,如success

xmlhttpRequest:http请求对象

 

type:结果返回类型,包括:xml、html、text、script、json、jsonp

 

 

*********************

示例

 

HelloController

@RestController
public class HelloController {

    @RequestMapping("/hello")
    public String hello(){
        return "hello 瓜田李下";
    }

    @RequestMapping("/hello2")
    public String hello2(String name){
        return "hello "+name;
    }

    @RequestMapping("/hello3")
    public Map<String,String> hello3(String name){
        Map<String,String> map=new HashMap<>();
        map.put("info",name);

        return map;
    }
}

 

index.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="/jquery/jquery-3.5.1.min.js"></script>
</head>
<script>
    $(function () {
        $("#btn").click(function () {
            $.post({
                url: "/hello2",
                data: {
                    name: "海贼王"
                },
                success: function (result) {
                    $("#span").html("<strong style='color: orange'>"+result+"</strong>")
                }
            })

            $.get({
                url: "/hello3",
                data: {
                    name: "海贼王"
                },
                success: function (result) {
                    $("#span2").css("color","green").text(result.info);
                }
            })
        })
    })
</script>
<body>
<div th:align="center">
    <span id="span"></span><br>
    <span id="span2"></span><br>
    <button id="btn">加载数据</button>
</div>
</body>
</html>

 

 

点击btn

                       

 

 


版权声明:本文为weixin_43931625原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。