使用admin.req发送纯JSON字符串请求

分享 未结 0 143
superch
悬赏:20飞吻
修改源码 src/lib/view.js



扩展后的 view.req 即 admin.req 模块的代码
  //Ajax请求
view.req = function(options){
var that = this
,success = options.success
,error = options.error
,request = setter.request
,response = setter.response
,debug = function(){
return setter.debug
? '<br><cite>URL:</cite>' + options.url
: '';
};

options.data = options.data || {};
options.headers = options.headers || {};

if(request.tokenName){
// Ajax请求扩展(增加纯JSON请求的处理逻辑)
// json请求的情况(只对应默认token的情况)
if (options.contentType && options.contentType.indexOf('application/json') != -1) {
// 自动给URL传入默认 token
var url = options.url;
if (url.indexOf('?') != -1) {
options.url = url + '&' + request.tokenName + '=' + (layui.datrequest.tokenName || '');
} else {
options.url = url + '?' + request.tokenName + '=' + (layui.datrequest.tokenName || '');
}

//自动给 Request Headers 传入 token
options.headers[request.tokenName] = (layui.datrequest.tokenName || '');

// 表单请求的情况
} else {
//自动给参数传入默认 token
options.data[request.tokenName] = request.tokenName in options.data
? options.data[request.tokenName]
: (layui.datrequest.tokenName || '');

//自动给 Request Headers 传入 token
options.headers[request.tokenName] = request.tokenName in options.headers
? options.headers[request.tokenName]
: (layui.datrequest.tokenName || '');
}
}

delete options.success;
delete options.error;

return $.ajax($.extend({
type: 'get'
,dataType: 'json'
,success: function(res){
var statusCode = response.statusCode;

//只有 response 的 code 一切正常才执行 done
if(res[response.statusName] == statusCode.ok) {
typeof options.done === 'function' && options.done(res);
}

//登录状态失效,清除本地 access_token,并强制跳转到登入页
else if(res[response.statusName] == statusCode.logout){
view.exit();
}

//其它异常
else {
var error = [
'<cite>Error:</cite> ' + (res[response.msgName] || '返回状态码异常')
,debug()
].join('');
view.error(error);
}

//只要 http 状态码正常,无论 response 的 code 是否正常都执行 success
typeof success === 'function' && success(res);
}
,error: function(e, code){
var error = [
'请求异常,请重试<br><cite>错误信息:</cite>'+ code
,debug()
].join('');
view.error(error);

typeof error === 'function' && error(res);
}
}, options));
};
使用例:
              admin.req({
url: '../api/village/save'
,type: 'POST'
,contentType: 'application/json; charset=utf-8'
,data: JSON.stringify({
userid: '10001',
username: 'admin',
data: field
})
,dataType: 'json'
,success: function(resp){
layer.close(index); //执行关闭
layui.table.reload('LAY-user-manage'); //重载表格
}
});
回帖
  • 消灭零回复