我对JavaScript很新,所以问题可能是假的。 我在代码中做了很多GET和POST请求,所以我决定编写包装函数来调用jQuery的ajax函数
/**
* Makes Get request
* @param url URL
* @param successCallback function triggered when request is successfully proceeded
* @param failCallback function triggered is case of failed request
*/
function getRequest(url,successCallback,failCallback){
$.ajax({
url: url,
timeout: 3000,
dataType: "json",
success: function(data,textStatus,jqXHR){
successCallback(data,textStatus,jqXHR);
},
error: failCallback(jqXHR,textStatus,errorThrown)
});
}
我这样称呼它:
url = "/api/info";
function onSuccess(data,textStatus,jqXHR){
$("#result").html("Hostname is "+data.hostname);
}
function onFail(jqXHR,textStatus,errorThrown){
$("#result").html("Shit happens");
}
//fire request
getRequest(url,onSuccess(),onFail());
触发回调,但数据未定义。
答案 0 :(得分:3)
最后我通过重写这样的函数来修复它:
function getRequest(url,successCallback,failCallback){
$.ajax({
url: url,
timeout: 3000,
dataType: "json",
success: function(data,textStatus,jqXHR){
successCallback(data,textStatus,jqXHR);
},
error: function(jqXHR,textStatus,errorThrown){
failCallback(jqXHR,textStatus,errorThrown);
}
});
}
用法是:
getRequest(url,onSuccess,onFail);
正如@Fabricator指出的那样