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

本文通过五个实例展示了如何使用jQuery简化AJAX请求,包括GET和POST方法,并提供了原生JavaScript实现相同功能的对比代码。

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

针对前端入门小白,如果直接上源生javascript请求(XMLHttpRequest、ActiveXObject),十有八九都会懵。所以在这里使用jquery展示几个常用ajax请求作为参考。

案例一:$.get请求

php代码

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

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>
案例二: $.post请求

php代码

<?php
    if ($_POST) {
        $id = $_POST['id'];
        $name = $_POST['name'];
        echo json_encode('name=' . $name . ',id=' . $id);
    }
?>

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>
案例三:$.ajax请求

php代码

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

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>
案例四:源生js的get请求

php代码

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

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>
案例五: 源生js的post请求

php代码

<?php
    if ($_POST) {
        $id = $_POST['id'];
        $name = $_POST['name'];
        echo json_encode('name=' . $name . ',id=' . $id);
    }
?>

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值