封装 jQuery 的 Ajax

175 阅读1分钟
$(function() {
				
        async function initData(){
                var opt ={
                        url:"https://v0.yiketianqi.com/api",
                        beforeSend:()=>{
                                console.log("开始发送!");
                        }
                }
                let res = await requestApi(opt);
                console.log(res);
        }
        initData();
});
// ajax请求
function requestApi(opt) {
        return new Promise((resolve, reject) => {
                $.ajax({
                        type: opt.type || 'get',
                        url: opt.url,
                        data: opt.data || {},
                        headers: opt.headers || {},
                        beforeSend: opt.beforeSend,
                        dataType: opt.dataType || "json",
                        success: (res) => {
                                resolve(res);
                        },
                        error: (err) => {
                                reject(err);
                        }
                });
        });
};