分享帮助文档ajax.js

    //ajax的目的就是发送请求参数,获取返回的响应内容
    // 功能:发请求,接响应
    // 参数:
    // type : get /post
    // url
    // isAsyn  true /false
    // data:key1=value1&key2=value2   无参 ""
    // callBack

    function ajaxFun(type,url,isAsyn,data,callBack){
        //1.
        let xhr = new XMLHttpRequest();

        type = type.toLowerCase();

        if(type == "get"){
            let urlParam = url;
            if(data != ""){
                //test.php?name=laowang&pwd=666
                urlParam += `?${data}`;
               
            }
            xhr.open(type,urlParam,isAsyn);
            xhr.send();
        }else if(type == "post"){
            xhr.open(type,url,isAsyn);
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            if(data != ""){
                xhr.send(data);
            }else{
                xhr.send();
            }
        }else{
            console.log("haha");
            return ;
        }

        //4.
        xhr.onreadystatechange = function(){
            if(xhr.readyState==4 && xhr.status==200){
                //5.
                callBack(xhr.responseText);
            }
        }
    }
posted @ 2022-07-28 20:45  AIR_Prelude  阅读(38)  评论(0)    收藏  举报