ajax实践

2017-04-04  本文已影响0人  S级食材咩咩羊

1.ajax 是什么?有什么作用?

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

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

var AjaxLocking = true;
//点击事件监听函数
xxx.addEventListener('clock',function(){
  if(!AjaxLocking){
    return;
  }
  xhr.onreadystatechange = function(){ //事件
    if(xhr.readyState === 4){
      //...
    AjaxLocking = true;
    }
 } 
  xhr.open()
  xhr.send()
  AjaxLocking = false;
})

4.封装一个 ajax 函数,能通过如下方式调用。后端在本地使用server-mock来 mock 数据

function ajax(opts){
    opts.success = opts.success || function () {};
    opts.error = opts.error || function () {};
    opts.type = opts.type || 'get';
    opts.dataType = opts.dataType || {};
    opts.data = opts.data || {};
    var dataStr = '';
    for (var key in opts.data)
    {
        dataStr += key + '=' + opts.data[key] + '&';
    }
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200 || xmlhttp.status == 304) {
                if (opts.dataType === 'text') {
                    opts.success(xmlhttp.responseText);
                }
                if (opts.dataType === 'json') {
                    var json = JSON.parse(xmlhttp.responseText);
                    opts.success(json);
                }
            } else {
              opts.error();
            }
        }
    };

    dataStr = dataStr.substr(0, dataStr.length - 1);

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

5.实现加载更多的功能,效果范例107,后端在本地使用server-mock来模拟数据

GitHub

上一篇 下一篇

猜你喜欢

热点阅读