关于JavaScript函数调用其他函数的笔记

来源:互联网 发布:制作地图的软件 编辑:程序博客网 时间:2024/05/16 00:29

今天一个项目用到了很多Ajax,很多地方都是用同一套Ajax套路,只不过对返回值的处理不一样,所以我把Ajax部分单独提出来写成一个函数以供调用:

function ajax(success_info, failed_info, success_func, failed_func, error_func, open_txt){    var xmlhttp;        if(window.XMLHttpRequest){            xmlhttp = new XMLHttpRequest();        }else{            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");        }        xmlhttp.onreadystatechange = function(){            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){                if(xmlhttp.responseText == success_info){                success_func();                }else if(xmlhttp.responseText == failed_info){                failed_func();                }else{                error_func();                }            }        }        xmlhttp.open("get", open_txt, true);        xmlhttp.send();    }
需要调用这个函数时,可以这么写:

function logout(){        ajax("pass", "failed", my_success_func, my_failed_func, my_error_func, "takelogout.php");        function my_success_func(){        //成功后执行的函数        }        function my_failed_func(){        //失败后执行的函数        }        function my_error_func(){        //出错后执行的函数        }    }
经验教训:函数作为参数时,无论是调用自己的函数的声明/定义还是被调用都不用加括号,只有在自己声明/定义时才需要加。

0 0
原创粉丝点击