原生ajax封装、ajax

AJAX(Asynchronous Javascript And XML) = 异步 JavaScript + XML 在后台与服务器进行异步数据交换,不用重载整个网页,实现局部刷新。

创建 ajax 步骤:

1.创建 XMLHttpRequest 对象
2.创建一个新的 HTTP 请求,并指定该 HTTP 请求的类型、验证信息
3.设置响应 HTTP 请求状态变化的回调函数
4.发送 HTTP 请求
5.获取异步调用返回的数据
6.使用 JavaScript 和 DOM 实现局部刷新

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
        fn.call(this, xhr.responseText);
    }
};
xhr.send(data);
//完整封装
function ajax(method, url, data, callback, flag) {
    //创建一个ajax对象  但是要兼容IE
    var xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Micro soft.XMLHttp');
    }

    //请求方式不同时的兼容性写法
    method = method.toUpperCase(); //兼容大小写,避免传入小写不显示
    if (method == 'GET') {
        xhr.open(method, url + '?' + data, flag);
        xhr.send();
    } else if (method == 'POST') {
        xhr.open(method, url, flag);
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
        xhr.send(data);
    }
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                callback(xhr.responseText);
            } else {
                console.log('error');
            }
        }
    }
}    
// jQuery $.ajax()
// 两种写法
// 写法一
$('#input_box').on('input', function () {
    var value = this.value;
    $.ajax({
        type: 'GET', //请求类型
        url: 'http://wuzhe128520.xicp.net:40038',
        // url:' https://api.douban.com/v2/music/search',
        success: function (res) {
            console.log(res)
        }
    })
})

 // 写法二:GET请求,jq提供的简化版
  $(function (){
    S.get('http://wuzhe128520.xicp.net:40038',function(res){
        console.log(res)
    })
})
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值