ajax 第四节 get参数传递 post请求体设置

========================  get参数传递 ==========================

<!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>AJAX GET 请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px red;
        }
    </style>
</head>

<body>
    <button>点击发送请求</button>
    <div id="result"></div>
</body>
<script>
    const btn = document.getElementsByTagName('button')[0];
    const result = document.getElementById('result');
    btn.onclick = function () {
        //创建对象
        const xhr = new XMLHttpRequest();
        //初始化,设置请求方法和 URL
        xhr.open('GET', 'http://127.0.0.1:8000/servers?a=100&b=200');
        //发送
        xhr.send();
        //事件绑定,处理服务器返回结果
        //on when 当……。时候
        //readystate 是xhr对象中的属性,表示状态0,1,2,3,4
        //,0(没有初始化),1(open方法调用完毕),2(send方法调用完毕),3(服务端返回了部分结果),4(服务端返回了所有结果)
        xhr.onreadystatechange = function () {
            //判断服务端是否返回了所有结果
            if (xhr.readyState == 4) {
                //判断响应状态是否成功(大于等于200小于300成功)
                if (xhr.status >= 200 && xhr.status < 300) {
                    console.log(xhr.status);//状态码
                    console.log(xhr.statusText);//状态字符串
                    console.log(xhr.getAllResponseHeaders());//所有响应头
                    console.log(xhr.response);//响应体
                    result.innerHTML = xhr.response
                } else {

                }
            }
        }
    }
</script>

</html>
 
=======================post 请求体设置 =========================
 
<!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>AJAX POST 请求</title>
    <style>
        #result {
            width: 200px;
            height: 100px;
            border: solid 1px red;
        }
    </style>
</head>

<body>
    <div id="result"></div>
</body>
<script>
    const result = document.getElementById("result");
    result.addEventListener("mouseover", function () {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://127.0.0.1:8000/servers');
        //1、  xhr.send('a=100&b=200&c=300');
        xhr.send('a:100&b:200&c:300');
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status >= 200 && xhr.status < 300) {
                    result.innerText = xhr.response;
                }
            }
        }
    })
</script>

</html>
=====================参数查看==========================

 

 

posted @ 2021-11-04 16:32  金在线  阅读(404)  评论(0编辑  收藏  举报