ajax请求,$.ajax,jQuery.ajax,$.get,$.post简易用法

本文通过五个实例详细介绍了前端使用jQuery及原生JavaScript进行Ajax请求的方法,包括GET和POST请求的具体实现,展示了如何与后端PHP交互获取JSON数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

案例一:$.get请求

php代码

<?php
    if ($_GET && $_GET['id'] == 5) {
        $arr = ['a' => 'apple', 'b' => 'banana'];
        echo json_encode($arr); //将$arr转成json字符串并输出
    }
?>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

html+js

<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>$.get测试</title></head>
<body>
<h3>测试页面</h3>
<button id="btn">$.get测试</button>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(function () {
        var btn = $('#btn');
        var post = $('#post');
        btn.click(function () {
            $.get('./admin/test.php?id=5', function (response, status) {
                if (status === 'success') {
                    console.log(response); //{"a":"apple","b":"banana"} (json字符串,需要手动转)
                } else {
                    alert('请求失败!');
                }
            })
        });
    })
</script>
</body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
案例二: $.post请求

php代码

<?php
    if ($_POST) {
        $id = $_POST['id'];
        $name = $_POST['name'];
        echo json_encode('name=' . $name . ',id=' . $id);
    }
?>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

html+js代码

<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>$.post测试</title></head>
<body>
<h3>测试页面</h3>
<button id="btn">$.post测试</button>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(function () {
        var btn = $('#btn');
        btn.click(function () {
            var data = {id: 3, name: 'zhangsan'};
            $.post('./admin/test.php', data, function (response, status) {
                if (status === 'success') {
                    console.log(response); //"name=zhangsan,id=3"
                } else {
                    alert('请求失败!');
                }
            })
        })
    })
</script>
</body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
案例三:$.ajax请求

php代码

<?php
    if ($_GET && $_GET['id'] == 5) {
        $arr = ['a' => 'apple', 'b' => 'banana'];
        echo json_encode($arr);
    }
?>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

html+js代码

<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>$.ajax测试</title></head>
<body>
<h3>测试页面</h3>
<button id="btn">$.ajax测试</button>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(function () {
        var btn = $('#btn');
        var data = {id: 5, name: 'wangwu'};
        btn.click(function () {
            $.ajax({
                type: "GET", //请求方式
                url: "./admin/test.php", //请求地址
                data: data, //data为请求数据
                dataType: "json", //设置返回结果为json格式
                success: function (response) {
                    console.log(response); //{a: "apple", b: "banana"} (json对象)
                }
            });
        });
    })
</script>
</body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
案例四:源生js的get请求

php代码

<?php
    if ($_GET && $_GET['id'] == 5) {
        $arr = ['a' => 'apple', 'b' => 'banana'];
        echo json_encode($arr);
    }
?>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

html+js代码

<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>Title</title></head>
<body>
<h3>测试页面</h3>
<button id="btn">源生js的get请求</button>
<script>
    var btn = document.querySelector('#btn');
    btn.onclick = function () {
        myRequest('GET', './admin/test.php?id=5', function (data) {
            console.log(data); //{"a":"apple","b":"banana"}
        });
    };
    function myRequest(type, url, back) {
        var async = true, timer = null, xmlHttp;
        if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        } else {
            xmlHttp = new ActiveXObject(); //兼容低版本浏览器
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 || xmlHttp.status == 200) {
                var response = xmlHttp.responseText;
                if (response) {
                    if (timer) {
                        window.clearTimeout(timer);
                    }
                    timer = setTimeout(function () {
                        back(response);
                    });
                }
            }
        };
        xmlHttp.open(type, url, async);//async[boolean],true时为异步,false为同步
        xmlHttp.send();
    }
</script>
</body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
案例五: 源生js的post请求

php代码

<?php
    if ($_POST) {
        $id = $_POST['id'];
        $name = $_POST['name'];
        echo json_encode('name=' . $name . ',id=' . $id);
    }
?>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

html+js代码

<!DOCTYPE html><html lang="en">
<head><meta charset="UTF-8"><title>Title</title></head>
<body>
<h3>测试页面</h3>
<button id="btn">源生js的post请求测试</button>
<script>
    var btn = document.querySelector('#btn');
    btn.onclick = function () {
        var postData = {id: 3, name: 'zhangsan'};
        myRequest('POST', './admin/test.php', postData, function (data) {
            console.log(data); //"name=zhangsan,id=3"
        });
    };
    function resetStr(obj) {
        var str = '';
        for (var key in obj) {
            if (obj.hasOwnProperty(key)) {
                str += '&' + key + '=' + obj[key];
            }
        }
        return str.substr(1);
    }
    function myRequest(type, url, postData, back) {
        var async = true, timer = null, xmlHttp;
        postData = resetStr(postData);//转换数据结构
        if (window.XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest();
        } else {
            xmlHttp = new ActiveXObject();
        }
        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 || xmlHttp.status == 200) {
                var response = xmlHttp.responseText;
                if (response) {
                    if (timer) {
                        window.clearTimeout(timer);
                    }
                    timer = setTimeout(function () {
                        back(response);
                    });
                }
            }
        };
        xmlHttp.open(type, url, async);//async[boolean],true时为异步,false为同步
        xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');//设置这个可以像HTML表单那样POST数据
        xmlHttp.send(postData);
    }
</script>
</body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值