gpt4 book ai didi

javascript - 让 JS 函数执行简单的 AJAX true/false 请求并返回结果的最佳方法是什么

转载 作者:行者123 更新时间:2023-12-01 00:44:47 26 4
gpt4 key购买 nike

让 JS 函数执行简单的 AJAX true/false 请求并返回结果的最佳方法是什么。

我想在 JS 函数中执行一个简单的 AJAX 请求,检查用户 session 是否仍处于事件状态。该函数应等待 AJAX 请求完成并返回 true 或 false。

我使用 setInterval 实现了这一点但我不认为这是最好的方法。我尝试使用 jQuery $.when但我无法让函数返回结果。

function checkSessionIsStillActive(){
var result; //ajax result will be put in here. It will be undefined until ajax complete

$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(function( data ) {
// return the value
result = data.session_active;
});

// Do an interval loop check until the result is defined
var interval_check = setInterval(function(){
// Return the result as soon as we have it
if(result != undefined ){

// Clear this interval loop
clearInterval(interval_check);
// return the result to the calling function
return result;
}
}, 100);
}

最佳答案

您应该阅读有关异步 JavaScript 的内容,尤其是 Promise .

function checkSessionIsStillActive(){
return new Promise((resolve, reject) => {
$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(data => {
// return the value
result = data.session_active;
resolve(result);
});
});
}

如果你调用该函数,你就会执行

checkSessionIsStillActive().then(data => {
// result from function is available here
});

关于javascript - 让 JS 函数执行简单的 AJAX true/false 请求并返回结果的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57481246/

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