gpt4 book ai didi

javascript - 我可以多次使用 jquery 的 .done() 吗?

转载 作者:行者123 更新时间:2023-11-29 22:07:33 25 4
gpt4 key购买 nike

我有 2 个 JS 文字:

var obj1 = {
Add: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/add",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};
var obj2 = {
List: function (id) {
$.ajax({
type: "POST",
data: JSON.stringify({
"id": id
}),
url: "Page.aspx/list",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
return jQuery.parseJSON(data.d || "null");
}
});
}
};

这是我的文档。准备就绪:

$(document).ready(function () {
obj1.Add(1).done(function (data) {
alert('you added ' + data);
});

obj2.List().done(function (data) {
$.each(jQuery.parseJSON(data), function (i, item) {
// fill a combo box
});
});
});

jQuery 只执行第一个调用,根本没有调用 obj2.List()。在这种情况下如何正确使用延迟对象?

最佳答案

将您的AddList 函数更改为RETURN ajax 对象。

 Add: function (id) {
return $.ajax({..

 List: function (id) {
return $.ajax({...

这样 - 它会返回 jqXHR obj,它会返回延迟对象。这实现了 Promise 接口(interface),该接口(interface)具有:您正在寻找的回调。

编辑:

look at this simple example which does work :

var obj1 = {
Add: function (id) {
return $.ajax({
type: "get",
data: JSON.stringify({
"id": 1
}),
url: "http://jsbin.com/AxisAmi/1/quiet",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {


alert("at success --"+data.data)
}
});
}
};

obj1.Add(2).done(function (a){alert("at done --"+a.data);});

enter image description here

enter image description here

关于javascript - 我可以多次使用 jquery 的 .done() 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20074086/

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