gpt4 book ai didi

javascript - 将 ajax 错误和成功函数替换为传递给父函数的替代函数

转载 作者:行者123 更新时间:2023-11-28 18:58:33 25 4
gpt4 key购买 nike

我编写了以下 JavaScript 类:

var DbObject = Class.extend({
init: function(classname, id){
// do some init stuff
},
send: function(isError){
if(isError){
// do something else
}
else if(!uploading){ // global
var obj =$.parseJSON(JSON.stringify(this));
$.ajax({
type: "POST",
dataType: "json",
url: "ajaxManager.php",
data: {data:obj},
success: function(response) {
response.success=true;
if(response.callback) window[response.callback](response);
console.log(response);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
else{
console.log('waiting....');
var $this =this;
setTimeout(function(){$this.send(); }, 2000);
}
}
});

现在,我使用这样的类:

var object = new DbObject('PageSettings', rowId);
object.send();

我希望也能够像这样使用它:

var object = new DbObject('PageSettings', rowId);
object.send(false, {
success: function (response) {
// some alternate code to run instead of the ajax `success: function`
},
error: function (xhr, status, error) {
// some alternate code to run instead of the ajax `error: function`
}
});

调用 .send() 时提供的 { success://...., error://...} 应替换 { success://..., error://...} 在它进行的 ajax 调用中。

实现这一目标的正确方法是什么?

最佳答案

像这样更改发送函数:

send: function (isError,handlers) {
if (!handlers) handlers = {};

if (!uploading) {
var obj = $.parseJSON(JSON.stringify(this));
$.ajax({
type: "POST",
dataType: "json",
url: "ajaxManager.php",
data: {
data: obj
},
success: handlers.success || function (response) {
....
},
error: handlers.error || function (xhr, status, error) {
....
}
});
} else {
....
}
}

关于javascript - 将 ajax 错误和成功函数替换为传递给父函数的替代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33080290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com