我是jQuery和Javascript的新手,所以这可能很简单。
我有一个使用$.ajax()
调用服务的函数。服务调用正常工作,但现在是时候回去清理一些东西了。例如,每当我调用服务时,我都会创建一个新函数并复制/粘贴一堆代码。我知道不好的做法,但我是原型。
我想要一个调用服务的函数,并将该函数传递给回调函数的名称。在下面的代码中,我想传递成功,错误和完成时要调用的函数的名称。我也希望将参数传递给函数。例如,我希望成功调用函数GetCurrentPricing
,并希望将响应传递给GetCurrentPricing
函数。
我该怎么做?
function CallTheService() {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : function(response) {},
error : function(err) {},
complete : function() {}
}
)
}
答案 0 :(得分:1)
您只需在以下位置调用该功能:
success: function(response){
GetCurrentPricing(response)
},
这些选项适用于:)
答案 1 :(得分:0)
做类似的事情:
success: function(response) {GetCurrentPricing(whateverparameters)},
答案 2 :(得分:0)
我会做类似的事情:
var success = function(response) { alert(response); };
function CallTheService(success) {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : function(response) { success.call(response); },
error : function(err) {},
complete : function() {}
}
)
}
答案 3 :(得分:0)
这样的事情应该有效:
var successFunction = function(response) { GetCurrentPricing(); };
function CallTheService(successFunction) {
$.ajax(
{
url : varUrl,
type : varType,
cache : varCacheBool,
data : varData,
contentType : varContentType,
processdata : varProcessData,
dataType : varDataType,
async : varAsync,
success : successFunction,
error : function(err) {},
complete : function() {}
}
)
}