发表于: 2016-11-29 00:43:15

7 1951


今天完成的事情:

今天看了改版的任务5要求,大体和以前一样,之前的任务内容好多靠猜,JS任务相对CSS任务差别很大,看不明白卡很久,对积极性有点儿打击。改版后明了多了,赞~ Jquery的AJAX已经做过了,很方便,原生AJAX还是挺重要,看了几个网站都用了原生,复习一下:

ajax应用场景:

  • 场景 1. 数据验证
  • 场景 2. 按需取数据
  • 场景 3. 自动更新页面
  • 使用XMLHttpRequest(ajax核心)来和服务器进行异步通信。

XmlHttpRequest对象属性

XmlHttpRequest对象方法:


创建AJAX步骤:


通过XmlHttpRequest对象向服务器发异步请求,从服务器获得数据,然后用javascript来操作DOM而更新页面。原生创建ajax可分为以下四步:

1、创建XMLHttpRequest对象:


var xhr = new XMLHttpRequest();


若考虑老版本IE兼容性,则:


function createRequest (){

    try {

        xhr = new XMLHttpRequest();

    }catch (tryMS){

        try {

            xhr = new ActiveXObject("Msxm12.XMLHTTP");

        } catch (otherMS) {

            try {

                xhr = new ActiveXObject("Microsoft.XMLHTTP");

            }catch (failed) {

                xhr = null;

            }

        }

    }

    return xhr;

}


2、准备请求


初始化XMLHttpRequest


xhr.open(method,url,async);


第一个参数可以为GETPOST,第三个参数为布尔值,表示请求是以异步还是同步的模式发出。(默认为true,一般不建议为false);


3、发送请求:


xhr.send();


GET方法一般用于传送少量数据(字符串等),可以用URL传参,这里send方法的参数为null或者空:

xhr.open("GET",url(含参),true);

xhr.send(null);


表单数据用POST,用 setRequestHeader()来添加 HTTP 头,然后在send()所要发送的数据:

xhr.open("POST",url,true);

xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

xhr.send(data);


4、处理响应:


xhr.onreadystatechange = function(){

    if(xhr.readyState == 4 && xhr.status == 200){

        console.log(xhr.responseText);

    }

}

onreadystatechange :当处理过程发生变化的时候执行函数;

readyState :ajax处理过程(状态码:0-4);

status属性:200:"OK"    404: 未找到页面;

responseText:获得字符串形式的响应数据;

responseXML:获得 XML形式的响应数据;

一般返回值为 JSON 数据,根据需求转化(JSON.stringify()JSON.parse()


完整的过程:

function ajax(url, success, fail){

    // 1. 创建连接

    var xhr = null;

    xhr = new XMLHttpRequest()

    // 2. 连接服务器

    xhr.open('get', url, true)

    // 3. 发送请求

    xhr.send(null);

    // 4. 接受请求

    xhr.onreadystatechange = function(){

        if(xhr.readyState == 4){

            if(xhr.status == 200){

                success(xhr.responseText);

            } else { // fail

                fail && fail(xhr.status);

            }

        }

    }

}


明天计划的事情:


继续任务问题;

遇到的问题:

task5接口文档没发现关于注册和登录的接口,数据从哪儿验证.......用户名和密码


收获:原生ajax


返回列表 返回列表
评论

    分享到