使用Mock拦截AJAX请求并返回数据--boldiy

2024-03-11  本文已影响0人  boldiy
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script src="https://cdn.bootcss.com/Mock.js/1.0.0/mock-min.js"></script>
    <script>
        //生成返回的Mock数据
        var { newList } = Mock.mock({
            'newList|20-30': [
                {
                    id: "@increment(1)",
                    title: '@cname',
                    age: '@natural(1,30)',
                    info: '@cparagraph(5,10)',
                }
            ]
        })

        //拦截Ajax请求
        Mock.mock('https://mes.taijuyun.com/api/list', 'get', () => {
            return {
                newList
            }
        })

        //请求数据
        const xhr = new XMLHttpRequest();
        xhr.open("get", 'https://mes.taijuyun.com/api/list', true);
        xhr.send();
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(JSON.parse(xhr.responseText))
            }
        }

    </script>
</body>

</html>
上一篇下一篇

猜你喜欢

热点阅读