Ajax

2018-02-21  本文已影响0人  黑色的五叶草

Ajax 是什么?有什么作用?

基础示例:

<div id="mydiv">你的名字</div>
<button id="btn">修改内容</button>


<script type="text/javascript" language="javascript">
    document.getElementById('btn').addEventListener('click', function () {
        var XMLHttp = new XMLHttpRequest();
        XMLHttp.onreadystatechange = function () {
            if (XMLHttp.readyState === 4 && XMLHttp.status === 200) {
                dealwith();
            }
        }

        XMLHttp.open('GET', './text.php', true);
        XMLHttp.send();
    })

    function dealwith() {
        document.getElementById('mydiv').innerHTML = XMLHttp.responseText;
    }

AJAX封装

    document.querySelector('#btn').addEventListener('click', function(){
        ajax({
            url: '/login',   //接口地址
            type: 'get',               // 类型, post 或者 get,
            data: {
                username: 'xiaoming',
                password: 'abcd1234'
            },
            success: function(ret){
                console.log(ret);       // {status: 0}
            },
            error: function(){
               console.log('出错了')
            }
        })
    });

        function ajax(opts){
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4 && xhr.status === 200){
                    var aa = JSON.parse(xmlhttp.responseText);
                    opts.success(aa);
                }else if(xhr.readyState === 4 && xhr.status !== 200){
                    opts.error();
                }
            }

            var dataStr = '';
            for(var key in opts.data){
                dataStr = dataStr + key + '=' + opts.data[key] + '&'
            }
            dataStr = dataStr.substring(0, dataStr.length-1)
            
            if(opts.type.toLowerCase() === 'get'){
                xhr.open(opts.type, opts.url + '?' + dataStr, true);
                xhr.send();
            }
            if(opts.type.toLowerCase() === 'post'){
                xhr.open(opts.type, opts.url, true);
                xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
                xhr.send(dataStr);
            }
        }
上一篇 下一篇

猜你喜欢

热点阅读