通过Ajax异步请求数据

通过XMLHttpRequest对象的send()方法实现

<!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>
    <!-- 提交表单,会向服务器发送数据 -->
    <!-- GET方式的请求数据添加在url中 多个数据中间用&连接  每个数据是name=value的格式-->
    <form action="#" method="GET">
        <input type="text" name='user'>
        <input type="text" name='pwd'>
        <input type="submit">
    </form>
    <button id="btn">按钮</button>
</body>
<script src="../9.2/创建XMLHTTPRequest对象.js"></script>
<!-- 引入写好的适配浏览器的创建XMLHTTPRequest对象 -->
<script>
    var btn = document.getElementById('btn');
    btn.addEventListener('click',function(){
     
     
        var xhr = createXMLHttpRequest();
        xhr.onreadystatechange = function(){
     
     //监听通信状态
            console.log(xhr.status);
            if(xhr.readyState === 4 && xhr.status === 200){
     
     
                console.log(xhr.responseText);
            }
        }
        xhr.open('get','http://127.0.0.1:1877/Ajax/%E4%BB%A3%E7%A0%81/9.2/02%E6%B5%8B%E8%AF%95XMLHttpRequest%E5%AF%B9%E8%B1%A1.html');
        
        //向服务器发送请求数据
        //send(data)方法
        //data就是要向服务器发送的请求数据
        //两种情况  发送数据  不发送数据写null
        //发送数据的格式跟method规定的请求方法的一样
        //如果请求的方法为get和head,则send方法写成send(null)参数只能是null   
        xhr.send(data);
       
        //把这些接收到的结果更新到HTML页面上
    })
</script>
</html>

猜你喜欢

转载自blog.csdn.net/weixin_44492275/article/details/108508019
今日推荐