AJAX

作者: 块垒 | 来源:发表于2016-08-31 18:32 被阅读89次

    ajax 是什么?有什么作用?

    ajax通过原生的XMLHttpRequest对象发出HTTP请求,得到服务器返回的数据后,再进行处理。
    ajax可以无需刷新整个网页,而是对部分网页进行刷新。

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

    前后端进行开发前,要定义好接口以及数据形式等细节,已达到解耦效果。
    后端接口完成前,前端可以通过MOCKJS等工具模拟数据。

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

    通过设定标记

    var flag=false;
    tn.addEventListener('click', function(e) {
        //......
        flag = true;
        if(flag){
            return;
        }
    });
    

    在请求数据时,函数flag设为false,保证不重复点击

    代码

    1. 封装一个 ajax 函数,能通过如下方式调用
    function ajax(opts){
        // todo ...
    }
    document.querySelector('#btn').addEventListener('click', function(){
        ajax({
            url: 'getData.php',   //接口地址
            type: 'get',               // 类型, post 或者 get,
            data: {
                username: 'xiaoming',
                password: 'abcd1234'
            },
            success: function(ret){
                console.log(ret);       // {status: 0}
            },
            error: function(){
               console.log('出错了')
            }
        })
    });
    

    实现:

    function ajax(opts){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                var ret = JSON.parse(xmlhttp.responseText);
                opts.success(ret);
            }
            if(xmlhttp.status == 404){
                opts.error();
            }
        };
        var dataStr = '';
        for(var key in opts.data){
            dataStr += key + '=' + opts.data[key] + '&';
        }
        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();
        }
    }
    
    1. 实现如下加载更多的功能。效果如下: http://jrgzuoye.applinzi.com/作业安排/jscode/JS9-jqueryajax/1.html
      新浪云
      源码
    2. 实现注册表单验证功能效果如下:http://jrgzuoye.applinzi.com/作业安排/jscode/JS7-ajax/3.html
      新浪云
      源码

    相关文章

      网友评论

        本文标题:AJAX

        本文链接:https://www.haomeiwen.com/subject/lbcqettx.html