gpt4 book ai didi

javascript - 更改我的函数异步 : false to async: true with JQuery and Ajax

转载 作者:行者123 更新时间:2023-12-01 03:33:31 24 4
gpt4 key购买 nike

我在 javascript 类中创建了一个函数,该函数转到 php 文件并从数据库返回信息。

这个函数工作得非常好,但我尝试拥有 async: true, 的属性,但我的函数不能使用这个属性。 (我收到此警告消息:L'utilization d'XMLHttpRequest de façon synchrone sur le fil d'execution main est obsolète à Cause de son Impact negatif sur la navigation de l'utilisateur Final。) p>

你有什么想法吗,我怎样才能让它发挥作用?一位 friend 告诉我尝试使用“回调”,但我不知道它是如何工作的。

    getInfoFromDB: function() {
var info;
$.ajax({
url: "./fonctions/ajax/members.php",
type: "POST",
dataType: 'html',
success: function(data) {
info = data;
},
async: false,

});
return info;
}

最佳答案

您必须更改 getInfoFromDB() 以返回 info 以外的内容。例如,您可能 return a Promise反而。如果只是返回$.ajax()的返回值,您将得到一个类似 Promise 的东西,解析为 data

getInfoFromDB: function() {
return $.ajax({
url: "./fonctions/ajax/members.php",
type: "POST",
dataType: 'html',
});
}

但是您必须更新调用 getInfoFromDB() 的所有位置以支持异步行为。例如:

myObject.getInfoFromDB().then(function (info) {
doSomethingWith(info);
});

来自 jQuery.ajax() 的文档:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information).

关于javascript - 更改我的函数异步 : false to async: true with JQuery and Ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415492/

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