javascrip中ajax

移动端对加载速度要求比较高,由于jquery插件有270多k,无形中增加加载的速度,下面整理一下原生js中ajax:

解ajax的基础知识

(1)XMLHttpRequest 对象

  XMLHttpRequest对象是ajax的核心,通过XMLHttpRequest对象来向服务器发异步请求,从服务器获得数据,所有现代浏览器(IE7+、Firefox、Chrome、Safari、Opera)均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。  

  创建一个兼容的XMLHttpRequest对象代码如下:

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

(2)向服务器发送请求

xhr.open(method,url,async);
    //method:请求的类型;GET 或 POST
    //url:请求的URL
    //async:true(异步)或 false(同步)
xhr.send(string);
    //将请求发送到服务器
    //string:仅用于 POST 请求
 
//GET 比 POST 请求方式更简单也更快,并且在大部分情况下都能用
//在以下情况中,请使用 POST 请求:
    //无法使用缓存文件(更新服务器上的文件或数据库)
    //向服务器发送大量数据(POST 没有数据量限制)
    //发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

(3)服务器响应

   使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性获得来自服务器的响应。

 如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性。

 如果来自服务器的响应并非 XML,请使用 responseText 属性,responseText 属性返回字符串形式的响应。

(4)onreadystatechange 事件

当请求被发送到服务器时,我们需要执行一些基于响应的任务。每当 readyState 改变时,就会触发 onreadystatechange 事件。readyState 属性存有 XMLHttpRequest 的状态信息。

   XMLHttpRequest 对象的三个重要的属性:

    onreadystatechange  //存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数

    readyState  //存有 XMLHttpRequest 的状态, 从 0 到 4 发生变化     

    • 0: 请求未初始化
    • 1: 服务器连接已建立
    • 2: 请求已接收
    • 3: 请求处理中
    • 4: 请求已完成,且响应已就绪

    status  //200: "OK", 404: 未找到页面

  在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务, 当 readyState等于4 且 status为200 时,表示响应已就绪

xhr.onreadystatechange = function(){
    if( xhr.readyState == 4 && xhr.status == 200 ){
        //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML 
    }
};

(5)开始写一个完整的简单ajax

var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.onreadystatechange = function(){
    if( xhr.readyState == 4 && xhr.status == 200 ){
        //准备就绪 可以处理返回的 xhr.responseText 或者 xhr.responseXML 
    }
};
xhr.open(method,url,async);
xhr.send(string);

(6)实际项目中应用了检测app版本进行更新,大概代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <title>hello world</title>
    <script type="text/javascript">
var wgtVer=null;
function plusReady(){
    // Android处理返回键
    plus.key.addEventListener('backbutton',function(){
        if(confirm('确认退出?')){
            plus.runtime.quit();
        }
    },false);
    // 获取本地应用资源版本号
    plus.runtime.getProperty(plus.runtime.appid,function(inf){
        wgtVer=inf.version;
        console.log("当前应用版本:"+wgtVer);
    });
}
if(window.plus){
    plusReady();
}else{
    document.addEventListener('plusready',plusReady,false);
}
// 检测更新
var checkUrl="http://demo.dcloud.net.cn/test/update/check.php";
function checkUpdate(){
    plus.nativeUI.showWaiting("检测更新...");
    var xhr=new XMLHttpRequest();
    xhr.onreadystatechange=function(){
        switch(xhr.readyState){
            case 4:
            plus.nativeUI.closeWaiting();
            if(xhr.status==200){
                console.log("检测更新成功:"+xhr.responseText);
                var newVer=xhr.responseText;
                if(wgtVer&&newVer&&(wgtVer!=newVer)){
                    downWgt();    // 下载升级包
                }else{
                    plus.nativeUI.alert("无新版本可更新!");
                }
            }else{
                console.log("检测更新失败!");
                plus.nativeUI.alert("检测更新失败!");
            }
            break;
            default:
            break;
        }
    }
    xhr.open('GET',checkUrl);
    xhr.send();
}
// 下载wgt文件
var wgtUrl="http://demo.dcloud.net.cn/test/update/H5EF3C469.wgt";
function downWgt(){
    plus.nativeUI.showWaiting("下载wgt文件...");
    plus.downloader.createDownload( wgtUrl, {filename:"_doc/update/"}, function(d,status){
        if ( status == 200 ) { 
            console.log("下载wgt成功:"+d.filename);
            installWgt(d.filename);    // 安装wgt包
        } else {
            console.log("下载wgt失败!");
            plus.nativeUI.alert("下载wgt失败!");
        }
        plus.nativeUI.closeWaiting();
    }).start();
}
// 更新应用资源
function installWgt(path){
    plus.nativeUI.showWaiting("安装wgt文件...");
    plus.runtime.install(path,{},function(){
        plus.nativeUI.closeWaiting();
        console.log("安装wgt文件成功!");
        plus.nativeUI.alert("应用资源更新完成!",function(){
            plus.runtime.restart();
        });
    },function(e){
        plus.nativeUI.closeWaiting();
        console.log("安装wgt文件失败["+e.code+"]:"+e.message);
        plus.nativeUI.alert("安装wgt文件失败["+e.code+"]:"+e.message);
    });
}
    </script>
</head>
<body>
    Hello HBuilder for test update.<br/>
    <br/>
    version 1.0
    <br/><br/><br/>
    <button onclick="checkUpdate()">Check Update</button>
</body>
</html>
个性签名:别低头,王冠会掉,别后退,梦想会碎~~~~~
原文地址:https://www.cnblogs.com/lily1010/p/5330422.html