js实现ajax请求

js实现ajax请求,注意post和get 的区别

                           注意请求参数的区别

  只写了成功的部分,异常的部分没有写 

function ajaxFunc(method, url, async, data, callback) {
    var xhr = null;
    if (window.XMLHttpRequest) {  //兼容写法
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP")  
    }
    method = method.toLocaleUpperCase(); //将传入的参数都变成大写,避免下面判断失效
    if (method == 'POST') {
        xhr.open(method, url, async);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send(data);

    } else if (method == 'GET') {
        xhr.open(method, url + '?' + data, async);  //get方式下将参数拼接到url后面
        xhr.send();
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                if (callback) {
                    callback(xhr.responseText);    // 回调函数处理返回的数据
                } else {
                    alert(xhr.responseText)
                }


            }
        }
    }
}

post方式下参数直接在xhr.send中发送,在post方式下需要设置请求头xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

get方式下需要将参数拼接到url后面

实例应用方式如下:

两个实例:上面的是提交输入框的值

                  下面的是点击请求列表数据,并通过showList渲染到ul中

    <input type="text" name="username" id="user"></input>
    <input type="text" name="age" id="age"></input>
    <button id="btn">提交</button>

    <button id="btnList">get</button>
    <ul id="ulList"></ul>
  <script>
        var oBtn = document.getElementById('btn');
        var btnList = document.getElementById('btnList');
        
        oBtn.onclick = function () {
            var name = document.getElementById('user');
            var age = document.getElementById('age');
            var nameValue = name.value;
            var ageValue = age.value;
            data = 'username=' + nameValue + '&age=' + ageValue;
            ajaxFunc('post', 'post.php', true, data)
        }

        btnList.onclick = function () {
            ajaxFunc('get', 'getNews.php', true, '', showList)
        }

        function showList(data) {
            var ulList = document.getElementById('ulList');
            data = JSON.parse(data);
            var str = '';
            data.forEach(function (ele, index) {
                str += '<li>' + ele.title + '--' + ele.date + '</li>';
            })
            ulList.innerHTML = str;
        }

    </script>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值