XMLHttpRequest 2级学习

老版本的缺点

老版本的XMLHttpRequest对象有以下几个缺点:

  • 只支持文本数据的传送,无法读取和上传二进制文件。
  • 传送和接收数据时,没有进度信息,只能提示有没有完成。
  • 受到”同域限制”,只能向同一域名的服务器请求数据。

新版本的功能

新版本的XMLHttpRequest对象的一些新功能:

  • 可以设置HTTP请求的时限。
  • 可以使用FormData对象管理表单数据。
  • 可以上传文件。
  • 可以请求不同域名下的数据(跨域资源共享,Cross-origin resource sharing,简称 CORS)。
  • 可以获取服务器端的二进制数据。
  • 可以获得数据传输的进度信息。

FormData

XMLHttpRequest 2级定义了FormData类型,这为序列化表单以及创建与表单格式相同的数据提供了便利。
新建FormData对象:

var formData = new FormData();

为它添加表单项:

formData.append('name', 'lisi');
formData.append('age', 12);

最后,直接传送这个FormData对象。这与提交网页表单的效果,完全一样。

xhr.send(formData);

Demo:

<!DOCTYPE html>
<html>
<head>
    <title>FormData</title>
    <meta charset="utf-8">
</head>
<body>
    <p>Fill in the form below:</p>
    <form id="user-info">
        <label for="user-name">姓名:</label>
        <input type="text" id="user-name" name="user-name" /><br>
        <label for="user-email">Email:</label>
        <input type="text" id="user-email" name="user-email" /><br>
        <input type="button" value="Submit" onclick="submitData()" />
    </form>
    <script type="text/javascript">
        function createXHR(){
                    if(typeof XMLHttpRequest){
                        return new XMLHttpRequest();
                    }else if(typeof ActiveXObject){
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    }
        }
        function submitData(){
            var xhr = createXHR();
            xhr.onreadystatechange = function(event){
                if (xhr.readyState == 4){
                    if (xhr.status == 200 ){
                        console.log(xhr.responseText);
                    } else {
                        alert("Request was unsuccessful: " + xhr.status);
                    }
                }
            };

            xhr.open("post", "postexample.php", true);
            var form = document.getElementById("user-info");
            xhr.send(new FormData(form));
        }
    </script>
</body>
</html>

postexample.php

<?php
    header("Content-Type: text/plain");
    echo <<<EOF
Name: {$_POST['user-name']}
Email: {$_POST['user-email']}
EOF;
?>

使用FormData的方便之处在于:不必明确在xhr对象上设置请求头部,xhr对象能够识别传入的数据类型是FormData的实例,并配置适当的头部信息。

FormData对象也可以用来获取网页表单的值:

   var form = document.getElementById('myform');
  var formData = new FormData(form);
  formData.append('name', 'lisi'); // 添加一个表单项
  xhr.open('POST', form.action);
  xhr.send(formData);

超时设定

新版本的XMLHttpRequest对象,增加了timeout属性,可以设置HTTP请求的时限,表示请求在等待响应多少毫秒之后就停止。在给timeout属性属性设置一个数值后,如果在规定的时间内浏览器还没有接收到响应,那么就会触发timeout事件,进而会调用ontimeout事件处理程序。

Demo:

<!DOCTYPE html>
<html>
<head>
    <title>Timeout事件</title>
    <meta charset="utf-8">
</head>
<body>
    <script type="text/javascript">
        function createXHR(){
                    if(typeof XMLHttpRequest){
                        return new XMLHttpRequest();
                    }else if(typeof ActiveXObject){
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    }
        }
        var xhr = createXHR();
        xhr.onreadystatechange = function(event){
            try {
                if (xhr.readyState == 4){
                    if (xhr.status == 200){
                        alert(xhr.responseText);
                    } else {
                        alert("Request was unsuccessful: " + xhr.status);
                    }
                }
            } catch (ex){
                //assume handled by ontimeout
            }
        };

        xhr.open("get", "timeout.php", true);
        xhr.timeout = 1000;//给xhr对象设置了timeout属性,表示请求在等待响应1000毫秒之后停止
        xhr.ontimeout = function(){
            alert("Request did not return in a second.");
        };
        xhr.send(null);
    </script>
</body>
</html>

跨域资源共享(CORS)

新版本的XMLHttpRequest对象,可以向不同域名的服务器发出HTTP请求。这叫做”跨域资源共享”(Cross-origin resource sharing,简称CORS)。
使用”跨域资源共享”的前提,是浏览器必须支持这个功能,而且服务器端必须同意这种”跨域”。如果能够满足上面的条件,则代码的写法与不跨域的请求完全一样。

例如:

xhr.open('post', 'http://localhost/test.php',true);

进度事件

新版本的XMLHttpRequest对象,传送数据的时候,有一个progress事件,用来返回进度信息。
它分成上传和下载两种情况:
1.下载的progress事件属于XMLHttpRequest对象
2.上传的progress事件属于XMLHttpRequest.upload对象
有以下6个进度事件:

  • loadstart:在接收到响应数据的第一个字节时触发
  • progress:在接收响应期间持续不断地触发
  • error:在请求发生错误时触发
  • abort:在因为调用abort()方法而终止连续时触发
  • load:在接收到完整的响应数据时触发
  • loadend:在通信完成或者触发error、abort或load事件后触发

    每个请求都是从触发loadstart事件开始,接下来是一或多个progress事件,然后触发error、abort或load事件中的一个,最后以触发loadend事件结束。

Demo:

<!DOCTYPE html>
<html>
<head>
    <title>XHR Progress Event Example</title>
</head>
<body>
    <div id="status"></div>
    <script type="text/javascript">
        function createXHR(){
                    if(typeof XMLHttpRequest){
                        return new XMLHttpRequest();
                    }else if(typeof ActiveXObject){
                        return new ActiveXObject("Microsoft.XMLHTTP");
                    }
        }
//主要浏览器接收到了服务器的响应,不管其状态如何,都会触发load事件。
        window.onload = function(){
            var xhr = createXHR();
            xhr.onload = function(event){
                if (xhr.status == 200){
                    console.log(xhr.responseText);
                } else {
                    alert("Request was unsuccessful: " + xhr.status);
                }
            };
            xhr.onprogress = function(event){
                var divStatus = document.getElementById("status");
                if (event.lengthComputable){
                    divStatus.innerHTML = "Received " + event.position + " of " + event.totalSize + " bytes";
                }
            };
            xhr.open("get", "test.php", true);
            xhr.send(null);
        };
    </script>
</body>
</html>

test.php

<?php
    header("Content-Type: text/plain");
    header("Content-Length: 27");
    echo "Some data";
    flush();
    echo "Some data";
    flush();
    echo "Some data";
    flush();
?>

progress事件会在浏览器接收新数据期间周期性地触发。onprogress事件处理程序会接收到一个event对象,其target属性是XHR对象,包含三个额外的属性:

  • lengthComputable:表示进度信息是否可用的布尔值
  • position:表示已经接收的字节数
  • totalSize:表示根据Content-Length响应头部确定的预期字节数
    利用这些信息,我们可以为用户创建一个进度指示器

ajax无刷新上传

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ajax无刷新上传</title>
    <style type="text/css">
    #div1{
        width: 300px;
        height: 30px;
        border:1px solid #000;
        position: relative;
    }
    #div2{
        width: 0;
        height: 30px;
        background: #CCC;
    }
    #div3{
        width: 300px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        position: absolute;
        left: 0;
        top: 0;
    }
    </style>
</head>
<body>
<input type="file" id="myFile" name="" value="" placeholder="">
<input type="button" id="btn" name="" value="上传">
<div id="div1">
    <div id="div2"></div>
    <div id="div3">0%</div>
</div>
<script type="text/javascript">
var oBtn = document.getElementById("btn");//获取上传按钮
var myFile = document.getElementById("myFile");
var oDiv2 = document.getElementById("div2");
var oDiv3 = document.getElementById("div3");
oBtn.onclick = function(){
    //alert(myFile.value);//获取到的是file控件的value值,这个内容是显示给你看的文字,不是我们选择的文件
    //myFile.files 是file控件中选择的文件列表对象
    //alert(myFile.files);//[object FileList]

    //我们是要通过ajax把myFile.files[0]数据发送给后端
    //for (var attr in myFile.files[0]) {
    //console.log( attr + ' : ' + myFile.files[0][attr] );
    // }
    var xhr = new XMLHttpRequest();
    //监听上传完成事件
    //load事件在接收到完整的响应数据时触发
    xhr.onload = function(){
        alert("上传完成");
    }
    // 监听上传进度
    var oUpload = xhr.upload;
    oUpload.onprogress = function(e){
            //e.total:待发送的总量
            //e.loaded:已经发送的总量
            //oUpload.onprogress:上传
            //onprogress:下载
            console.log(e.total + ':' + e.loaded);
        var iScale = e.loaded / e.total;//获取已经上传的比例
            //上传进度条
            //根据上传的比例改变进度条div的宽度(初始宽度为0)
            oDiv2.style.width = 300 * iScale + 'px';
            //上传进度的百分比显示
            oDiv3.innerHTML = 100 * iScale + '%';
    };
    xhr.open('post','post_file.php',true);//post请求
    var oFormData = new FormData();
    //append方法接收两个参数:分别对象表单字段名称和表单字段值
    oFormData.append('file',myFile.files[0]);
    xhr.send(oFormData);
};
</script>
</body>
</html>

post_file.php

<?php
header('Content-type:text/html; charset="utf-8"');
//uploads--用来存放上传成功的文件
$upload_dir = 'uploads/';
//strtolower把所有字符转换为小写
//如果发送客户端发送的不是post请求,则给出相应的错误信息并退出
if(strtolower($_SERVER['REQUEST_METHOD']) != 'post'){
    exit_status(array('code'=>1,'msg'=>'错误提交方式'));
}
//检查键名是否存在于数组中
//array_key_exists(key,array),存在则返回true
//$_FILES['myFile']['error'] 和该文件上传相关的错误代码
if(array_key_exists('file',$_FILES) && $_FILES['file']['error'] == 0 ){
    $pic = $_FILES['file'];
    //move_uploaded_file() 函数将上传的文件移动到新位置
    //第一个参数表示要移动的文件,第二个参数为文件的新位置
    //若成功,则返回 true,否则返回 false
    if(move_uploaded_file($pic['tmp_name'], $upload_dir.$pic['name'])){
        exit_status(array('code'=>0,'msg'=>'上传成功','url'=>$upload_dir.$pic['name']));
    }
}
echo $_FILES['file']['error'];
exit_status(array('code'=>1,'msg'=>'出现了一些错误'));
//将关联数组转为json字符串,并退出
function exit_status($str){
    echo json_encode($str);
    exit;
}
?>
  • $_FILES[“file”][“name”] - 被上传文件的名称
  • $_FILES[“file”][“type”] - 被上传文件的类型
  • $_FILES[“file”][“size”] - 被上传文件的大小,以字节计
  • $_FILES[“file”][“tmp_name”] - 存储在服务器的文件的临时副本的名称
  • $_FILES[“file”][“error”] - 由文件上传导致的错误代码

用promise实现ajax

Demo:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ajax的Promise实现</title>
</head>
<body>
<script type="text/javascript">
function ajax(method,url,data,bool){
    var promise = new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.open(method,url,bool);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    resolve(xhr.responseText);
                }else{
                    reject(new Error(xhr.statusText));
                }
            }
        };
        // xhr.responseType = "json";
        // xhr.setRequestHeader("Accept", "application/json");
        xhr.send(data);
    });
    return promise;
}
ajax("get","http://localhost/mywork/promise/post.json",null,false).then(function(data){
    data = JSON.parse(data);//服务器返回的是一个json字符串
    console.log(data.name+"--"+data.age);//lisi--12
},function(error){
    console.error("出错了:"+error);//出错了:Error: Not Found
});
</script>
</body>
</html>

post.json

{
    "name":"lisi",
    "age":12
  }

Demo2:
模拟登陆实现

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>ajax_form</title>
</head>
<body>
<form id="myform">
<label for="name">用户名:</label>
<input type="text" name="user-name" id="user-name" placeholder="请输入你的用户名">
<label for="age">密码:</label>
<input type="password" name="user-password" id="user-password" placeholder="请输入你的年龄">
<input type="submit" value="登录" id="subBtn">
</form>
<script type="text/javascript">
var subBtn = document.getElementById("subBtn");
var form = document.getElementById("myform");
function ajax(method,url,data,bool){
    var promise = new Promise(function(resolve,reject){
        var xhr = new XMLHttpRequest();
        xhr.open(method,url,bool);
        xhr.onreadystatechange = function(){
            if(xhr.readyState == 4){
                if(xhr.status == 200){
                    resolve(xhr.responseText);
                }else{
                    reject(new Error(xhr.statusText));
                }
            }
        };
        xhr.send(data);
    });
    return promise;
}
subBtn.onclick = function(){
    ajax("post","http://localhost/mywork/promise/post.php",new FormData(form),false)
    .then(function(data){
        if(data == "ok"){
            alert("登录成功");
        }else{
            alert("用户名或者密码不正确");
        }
    },function(){
        console.error("出错了:"+error);
    });
};
</script>
</body>
</html>

post.php

<?php
 header("Content-Type: text/plain");
 $name = $_POST["user-name"];
 $pwd = $_POST["user-password"];
 if($name == "admin" && $pwd == "123"){
    echo "ok";
 }else{
    echo "no";
 }
 ?>

参考博文:
XMLHttpRequest Level 2 使用指南

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值