layui.define(['jquery'], function(exports) { var $ = layui.jquery; var url = location.origin + "/"; var base = url; var obj = { get: get, post: post, delete: del, put: put, authGet: authGet, authPost: authPost, authDelete: authDel, authPut: authPut // vid: '5d8864f7fc650e050cc8b0d7' } //封装AJAX请求 function ajax(type, url, data, success, auth) { var index = layer.load(0, { shade: false }); var headers = { 'X-CSRF-Token': $('meta[name=csrf-token]').attr('content'), "Content-Type": "application/json;charset=UTF-8" } $.ajax({ //添加请求头 headers: headers, url: base + url, dataType: "json", //数据格式 data: JSON.stringify(data), // JSON.stringify(data), traditional:true, type: type, //请求方式 // async: false, //是否异步请求 timeout: 30000, //超时时间:30秒 // beforeSend: function(XMLHttpRequest) { // var token = localStorage.getItem("auth"); // //发送请求,如果token为空,跳转到登录页面 // if (token === undefined || token === "") { // var url = window.document.location.href; // if (url.indexOf('login.html') > -1) {} else { // window.location.href = "/site_admin/login.html" // } // } // }, success: function(res) { return success(res); }, complete: function(XMLHttpRequest, textStatus) { layer.close(index); }, error: function(res) { if (res.responseJSON.msg) { layer.alert(res.responseJSON.msg, { icon: 5, title: "提示" }); } else { layer.alert('系统繁忙,请稍后', { icon: 5, title: "提示" }); } } }); } /** * 发送post请求 * @param {发送请求路径} url * @param {JSON数据} data * @param {发送成功回调函数} success */ function post(url, data, success) { ajax('post', url, data, function(res) { return success(res); }); } /** * 发送GET请求 * @param {发送请求路径} url * @param {JSON数据} data * @param {发送成功回调函数} success */ function get(url, data, success) { ajax('get', url, data, function(res) { return success(res); }); } function put(url, data, success) { ajax('put', url, data, function(res) { return success(res); }); } /** * 发送Delete请求 * @param {发送请求路径} url * @param {JSON数据} data * @param {发送成功回调函数} success */ function del(url, data, success) { ajax('delete', url, data, function(res) { return success(res); }); } function authGet(url, data, success) { ajax('get', url, data, function(res) { return success(res); }, true); } function authPost(url, data, success) { ajax('post', url, data, function(res) { return success(res); }, true); } function authPut(url, data, success) { ajax('put', url, data, function(res) { return success(res); }, true); } function authDel(url, data, success) { ajax('delete', url, data, function(res) { return success(res); }, true); } exports("request", obj); })