ajax--原生方式发起get无参请求,-原生方式发起get带参请求

127 阅读1分钟

原生方式发起get无参请求

<body>
    <button>获取数据</button>
    <script>
        let btn = document.querySelector('button')
        btn.addEventListener('click', function () {
            //创建xhr对象
            let xhr = new XMLHttpRequest()
            //请求行
            xhr.open('get', 'http://www.itcbc.com:3006/api/getbooks')
            //get方式无请求头
            //请求体 不可以写undefined 和函数 function
            xhr.send(null)
            //接收响应
            xhr.addEventListener('load', function () {
                console.log(xhr.response);
                console.log(JSON.parse(xhr.response), typeof JSON.parse(xhr.response));
            })
        })

       

    </script>
</body>

image.png

原生方式发起get带参请求

<body>
    <button>获取数据</button>
    <script>
        let btn = document.querySelector('button')
        btn.addEventListener('click', function () {
            //创建xhr对象
            let xhr = new XMLHttpRequest()
            //请求行
            xhr.open('get', 'http://www.itcbc.com:3006/api/getbooks?id=11590')
            //get方式无请求头
            //请求体
            xhr.send()
            //接收响应
            xhr.addEventListener('load', function () {
                console.log(JSON.parse(xhr.response));
            })
        })
    </script>
</body>

image.png