通过对ajax方法的封装,可以进一步简化ajax调用,方便统一管理路径。
var util = {}; util.RequesterClass = function() { this.send = function(p_options) { var defaultOptions = { type : "POST" }; var options = $.extend({}, defaultOptions, p_options); var params = options.params; if (options.params != null && options.type == "POST") { if (isPlainObject(options.params)) { params = JSON.stringify(options.params); } } var url = getRequestPath(options.path); $.ajax({ url : url, data : params, type : options.type, contentType : "application/json; charset=utf-8", beforeSend : _beforeSend }).done(function(p_result) { if (isFunction(options.complete)) { if (isPlainObject(p_result)) { options.complete(false, p_result); } else { options.complete(true, p_result); } } }).fail(function(p_request, textStatus, errorThrown) { var error = new Error("Error when accessing " + url); error.method = p_request.method; error.responseText = p_request.responseText; error.responseStatus = p_request.status; error.internalError = errorThrown; if (isFunction(options.complete)) { options.complete(false, error); } }); }; function getRequestPath(p_path) { var url = "http://10.128.174.26:8000/";// http://10.128.174.26:8000/UTM/v0/ return url + p_path; } function _beforeSend(p_request, p_options) { // var user = jQuery.sap.getObject("user"); // if (typeof (user) != undefined && user != null) { // p_request.setRequestHeader("AccessToken", user.AccessToken); // } } }; util.Requester = new util.RequesterClass();
封装的util.Requester方法需要调用的其他方法
function isPlainObject(p_value) { return $.isPlainObject(p_value); } function isFunction(p_value) { return typeof (p_value) == "function"; }
测试范例
util.Requester.send({ path : "UTM/v0/", params : {}, complete : function(p_successful, p_result){ if(p_successful) { sap.m.MessageBox.alert(p_result); } else { sap.m.MessageBox.alert(p_result.message); } } });