• js写一个ajax错误规避


    <!--在上一篇随笔中记录了51CTO视频中使用js创建一个原生态的简单ajax。
    于是突发奇想,希望能在每个元素中使用onclick事件来调用ajax。于是写了下面这个代码。
    (这个代码是错误的,在此记录只为防止以后再犯类似错误)-->
    <!DOCTYPE html>
    <html>
        <head>
            <script type="text/javascript">
                function ajaxfunc(){
                    var request;
                    if(window.XMLHttpRequest) {
                        request = new XMLHttpRequest();
                    }else{
                        request = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    var url = this.href;
                    alert("this.href:"+url);
                    var method = "GET";
                    request.open(method, url);
                    request.send(null);
                    request.onreadystatechange = function(){
                        if(request.readyState == 4){
                            if(request.status == 200 || request.status == 304){
                        //        document.getElementById("details").innerHTML = request.responseText;
                            }
                        }
                    }
                    return false;
                }
            </script>
        </head>
        <body>
            <h1>People</h1>
            <ul>
                <li><a onclick="ajaxfunc()" href="files/andy.html">Andy</a></li>
                <li><a onclick="ajaxfunc()" href="files/jimy.html">jimy</a></li>
                <li><a onclick="ajaxfunc()" href="files/lucy.html">lucy</a></li>
                <li><a onclick="ajaxfunc()" href="files/lily.html">lily</a></li>
            </ul>
            <div id="details"></div>
        </body>
    </html>
    
    <!--这种实现方式是不对的。函数ajaxfunc()中有个this, 定义了url=this.href。这样有语义上的错误。this指针使用于对象内部,在对象被
    实例化之后,调用对象内的方法时,可以用this,这里的ajaxfunc()函数是在元素当中使用onclick事件来调用的。这里并没有实例化任何对象。
    所以不能这么用。自己犯了这么低级的错误,浪费自己一天时间来查问题。特此记录,避免再犯。-->
  • 相关阅读:
    sass学习(1)——了解sass
    ES6学习(2)——arrows箭头函数
    ES6学习(1)——如何通过babel将ES6转化成ES5
    过年后的小计划
    JavaScript,通过分析Array.prototype.push重新认识Array
    JavaScript如何判断参数为浮点型
    gulp之静态资源防缓存处理
    递归算法,JavaScript实现
    有趣的Node爬虫,数据导出成Excel
    Memcached、Redis、RabbitMQ
  • 原文地址:https://www.cnblogs.com/flyfish919/p/6511676.html
Copyright © 2020-2023  润新知