天天看点

WEB数据传输——ajax加载数据

ajax的出现实现了前后端分离 记一些常用的ajax方法。

1、原生js实现全平台兼容XMLHttpRequest对象

function getXHR(){
    var xhr = null;
    if(window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("您的浏览器暂不支持Ajax!");
            }
        }
    }
    return xhr;
}
           

2、ajax实现文件上传

<input type="file" id="in">
<script>
    var input=document.getElementById("in");
    formData=new FormData();
    formData.append("file".input[]);
    var url="";
    method="POST";
    function ajax(url, method, data){
        var xhr = null;
        if(window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    xhr = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    alert("您的浏览器暂不支持Ajax!");
                }
            }
        }
        xhr.onerror = function(e){
            console.log(e);
        }
        xhr.open(method, url);
        try{
            setTimeout(function(){
                xhr.send(data);
            });
        }catch(e){
            console.log('error:',e);
        }
        return xhr;
    }
           

3、ajax请求图片

var xhr = new XMLHttpRequest(),
        url = ".png";
    xhr.open("GET", url);
    xhr.responseType = "newimg";
    xhr.onload = function(){
        if(this.status == ){
            var newimg = this.response;
            var img = document.createElement("img");
            img.src = window.URL.createObjectURL(newimg);//这里blob依然占据着内存
            img.onload = function() {
                window.URL.revokeObjectURL(img.src);//释放内存
            };
           

4、ajax请求文本

var xhr = new XMLHttpRequest();
xhr.open("GET","http://localhost:8080/Information/download.jsp?data=node-fetch.js");
xhr.responseType = "blob";
xhr.onload = function(){
  if(this.status == ){
    var blob = this.response;
    var reader = new FileReader();
    reader.readAsBinaryString(blob);//该方法已被移出标准api,建议使用reader.readAsText(blob);
    reader.onload=function(){
      document.body.innerHTML = "<div>" + this.result + "</div>";
    }
  }
}
xhr.send();
           

未完待续。。。。

继续阅读