JavaScript 在jQuery发送Ajax请求

前言:

在jQuery中发送Ajax请求的三种方法:

  1. get请求
  2. post请求
  3. 通用型方法Ajax

三种方法的具体使用看以下代码:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery发送Ajax请求</title>
    <link crossorigin="anonymous" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.1/css/bootstrap.css" rel="stylesheet">
    <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
    <div class="container">
        <h2 class="page-header">jQuery发送Ajax请求</h2>
        <button class="btn btn-primary">GET</button>
        <button class="btn btn-danger">POST</button>
        <button class="btn btn-info">通用型方法Ajax</button>
    </div>
    <script>
        $('button').eq(0).click(function() {
    
    
            $.get('http://127.0.0.1:8000/jquery-server', {
    
    
                a: 100,
                b: 200
            }, function(data) {
    
    
                console.log(data);
            }, 'json')
        })
        $('button').eq(1).click(function() {
    
    
            $.post('http://127.0.0.1:8000/jquery-server', {
    
    
                a: 100,
                b: 200
            }, function(data) {
    
    
                // console.log(data);
                console.log(data.name);
            }, 'json')
        })

        $('button').eq(2).click(function() {
    
    
            $.ajax({
    
    
                //url
                url: 'http://127.0.0.1:8000/jquery-server',
                //参数
                data: {
    
    
                    a: 1000,
                    b: 2000
                },
                //请求类型
                type: 'GET',
                //响应体结果
                dataType: 'json',
                //成功的回调
                success: function(data) {
    
    
                    console.log(data);
                },
                //超时时间
                timeout: 2000,
                //失败的回调
                error: function(data) {
    
    
                    console.log("出错了!!");
                },
                //头信息
                headers: {
    
    
                    c: 300,
                    d: 400
                }

            });
        })
    </script>
</body>

</html>

具体页面效果图如下

在这里插入图片描述
以上就是在jQuery中发送Ajax请求的三种方法,有不当之处可以在评论区指正!

猜你喜欢

转载自blog.csdn.net/lu202032/article/details/122290061