温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JavaScript的Ajax之GET提交数据

发布时间:2020-08-06 10:15:18 来源:网络 阅读:456 作者:瓶子小 栏目:web开发
<!DOCTYPE html>
<html>
<head>
    <title>封装ajax</title>
</head>
<body>

<!-- 05:59 ajax 下-->

<script type="text/javascript">

    function createXHR()
    {
        if(typeof XMLHttpRequest != "undefined")
        {
            return new XMLHttpRequest();
        }
        else if(typeof ActiveXObject != "undefined")
        {
            var versions = [
                "MSXML.2.XMLHttp.6.0",
                "MSXML.2.XMLHttp.3.0",
                "MSXML.2.XMLHttp"
            ];
            for(var i = 0; i<versions.length;i++)
            {
                try{
                    return new ActiveXObject(version[i]);
                }catch(e){
                    // 因类循环会报一个错,跳过些错
                }
            }
        }
        else
        {
            throw new Error("你的系统或浏览器不支持XHR对象!");
        }
    }

    // 名值对转换字符串
    function params(data)
    {
        var arr = [];
        for(var i in data)
        {
            arr.push(encodeURIComponent(i)+"="+encodeURIComponent(data[i]));    
        }
        return arr.join("&");
    }

    // ajax 

    function ajax(obj)
    {
        var xhr=createXHR();
        obj.url=obj.url+"?rand="+Math.random()+"&"+params(obj.data);
        obj.data = params(obj.data);
        if(obj.method === "GET")
        {
            obj.url=obj.url+"&"+obj.data;   
        }
        xhr.onreadystatechange = function()
        {
            if(xhr.readyState == 4)
            {                   
                if(xhr.status == 200)
                {               
                    obj.success(xhr.responseText)
                }
                else
                {
                    console.log("错误码:"+xhr.status+"-错误信息"+xhr.statusText);
                }
            }
        }
        xhr.open(obj.method,obj.url,obj.async);
        xhr.send(null);
    }

    //  use ajax

    addEventListener("click",function(){
        ajax({
            method:"GET",
            url:"test.php",
            data:{
                "na&me":"ping",
                "age":18
            },  
            // 将对象传到text,然后对象又回调
            success:function(text)
            {
                console.log("接收success数据为:"+text);
            },
            async:true
        });
    },false);
</script>
</body>
</html>
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI