ajax回调

68 阅读1分钟

手写代码块(需更改)

var obj = {
            methods: 'get',
            url: 'http://124.222.85.215:3009/url/api/www/banner/index/bannerList?httpsStatus=1&reqId=18f5c5f0-0bf4-11ee-86c3-f99f7af1c590'
        }

       //***
        ajax(obj, (data) => {
            console.log(data);
            data.data.forEach(item => {
                list.innerHTML += `<li>${item.pic}</li>`
            })
        });

后置js代码块(两者取其一)

 function ajax(config, callback) {
    let xhr = new XMLHttpRequest();
    xhr.open(config.methods, config.url);
        xhr.send();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4 && xhr.status == 200) {
           var res = JSON.parse(xhr.responseText);
           console.log(res);
           //ajax函数第二个参数自执行 把请求回来数据传到另一个页面
           callback(res);
        }
    }
    xhr=null;
}

后置jquery(两者取其一)

function ajax(config,callback){
    $.ajax({
        type: config.methods,
        url: config.url,
        headers: {
            Platformtype: "h5"
        },
        success: function (data) {
            console.log(JSON.parse(data));
            callback(JSON.parse(data))
        }
    })
}