Ajax

2017-02-14  本文已影响0人  BAMO

ajax是什么?有什么作用?

Ajax可以把它当做页面与后端交接的微桥梁,可以实现异步操作,无须刷新整个页面的情况下实现局部刷新,是前端开发人员必须掌握的一个技能;
大体步骤可以分为以下:
1.createXHR
2.xhr.open(type,url,boolean) //确定请求发送类型、URL、同步/异步
3.xhr.send() //发送到服务器

前后端开发联调需要注意哪些事情?后端接口完成前如何mock数据?

明确需要测试的数据,逻辑测试需要清晰,前端发送什么数据给后台,后头返回什么数据给前台,双方约定好;后端接口完成前,搭建服务器,mock数据,确定程序能跑起来。

点击按钮,使用 ajax 获取数据,如何在数据到来之前防止重复点击?

<script>
var ct = document.querySelector("#ct");
        btn = document.querySelector("#btn");



var lock = true;
function ajax(opts){
    lock = false;
    var xhr = new XMLHttpRequest();
    xhr.onredaystatechange = function(){
        if(xhr.readyState===4 && xhr.status===200){
            var result = JSON.parse(xhr.responseText);
            opts.success(xhr.responseText);
            lock = true;
        }else if(xhr.readyState===4 && xhr.status!==200) {
            opts.error();
            lock = true;
        }
    }
    var urlStr ="";
    for(var key in opts.data){
        urlStr = key +"="+opts.data[key]+"$";
    }
    urlStr = urlStr.substring(0,urlStr.length-1);

    if(opts.type.toLowerCase()==="get"){
        xhr.open(opts.type,opts.url+"?"+urlStr,true);
        xhr.send();
    }
    if(opts.type.toLowerCase()==="post"){
        xhr.open(opts.type,opts.url,true);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(urlStr)
    }
}


btn.addEventListener("click",function(){
    if(lock===true){
        ajax(
        {
            url:'/more',
            type: 'post',
            data: {
                len: document.querySelectorAll('li').length
            },
            success: function(data){
                console.log(data);
            },
            error: function(){
                console.log('出错了')
            }
        })
    }
})
</script>

题目5:实现加载更多的功能

代码

上一篇 下一篇

猜你喜欢

热点阅读