封装ajax的get和post函数,以及合并封装

1.ajax的get函数封装:

 function ajaxGet(url,cb){
        var xhr = new XMLHttpRequest();
        xhr.open("GET",url);
        xhr.send();
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                cb(xhr.responseText);
            }
        }
    }

2.ajax的post函数封装:

function ajaxPost(url,cb,data){
        var xhr = new XMLHttpRequest();
        xhr.open("POST",url);
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xhr.send(data);
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                cb(xhr.responseText);
            }
        }
    }

3.合并封装:


    document.onclick = function(){
        var url = "http://localhost/webRoot/ajax/data/get-post.php";//这是你根目录下的文件夹
        ajax({
            success:function(res){
                console.log(res);
            },
            url:url,
            type:"get",
            data:"user=admin&pass=123"
        });
    }
    function ajax(ops){
        ops.type = ops.type || "get";
        ops.data = ops.data || "";
        ops.url = ops.type=="get" ? ops.url + "?" + ops.data : ops.url;
        var xhr = new XMLHttpRequest();
        xhr.open(ops.type, ops.url);
        if(ops.type == "get"){
            xhr.send();
        }else{
            xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xhr.send(ops.data);
        }
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                ops.success(xhr.responseText);
            }
        }
    }

 get-post.php里面的内容如下:

<?php

    $u = $_REQUEST["user"];
    $p = $_REQUEST["pass"];

?>
发布了17 篇原创文章 · 获赞 7 · 访问量 247

猜你喜欢

转载自blog.csdn.net/qq_44381873/article/details/104808458