gpt4 book ai didi

jquery函数返回不起作用

转载 作者:行者123 更新时间:2023-12-01 06:54:35 25 4
gpt4 key购买 nike

Possible Duplicate:
jQuery: Return data after ajax call success

我有从另一个函数调用的以下函数。它需要返回一些东西才能查看该函数是否有效。

//Function to close any existing connection 
function closeConnection(manual) {
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/closeconnection.php',
success: function (feedback) {
//If this function was called manually, also empty chatTextDiv and fade out chatDiv
if (manual == true) {
//Stop getting messages
clearInterval(setintervalid);
//Fade out chatDiv
$('#chatDiv').fadeOut(100);
//Empty chatTextDiv
$('#chatTextDiv').html('');
//Fade in openChatDiv
$('#openChatDiv').fadeIn(100);
}
}
}).error(function () {
//Append with connection error - user doesn't know that he is disconnected first so it is better to say this as the function will return false and stop other functions
if (manual != true) {
$('#chatTextDiv').append('You could not be connected. Please try again later.<hr/>');
//Stop getting messages
clearInterval(setintervalid);
var closeconnectionsuccess = false;
}
elseif(manual == true) {
$('#chatTextDiv').append('You could not be disconnected. Please try again later.<hr/>');
var closeconnectionsuccess = true;
}
});

return closeconnectionsuccess;
}

实际上,我只想返回函数成功的最后一行:代码不起作用。为什么不呢?

最佳答案

正如 @Rockitsauce 所说,您的 closeconnectionsuccess 变量不在函数的范围内,因此此时无法访问。然而,更重要的是,您必须考虑到您正在使用 jQuery 的异步函数 - 函数 closeConnection 将在回调之前完成执行(success, error) 被调用。如果您想在 HTTP 请求完成后检索任何结果,您还必须向您自己的函数添加一个回调函数,从而使其异步。

因此,此代码应该有效:

//Function to close any existing connection 
function closeConnection(manual, callback) {
//Establish connection to php script
$.ajax({
type: 'POST',
url: 'action/chat/closeconnection.php',
success: function(feedback) {
//If this function was called manually, also empty chatTextDiv and fade out chatDiv
if(manual==true)
{
//Stop getting messages
clearInterval(setintervalid);
//Fade out chatDiv
$('#chatDiv').fadeOut(100);
//Empty chatTextDiv
$('#chatTextDiv').html('');
//Fade in openChatDiv
$('#openChatDiv').fadeIn(100);
}
}
}).error(function() {
//Append with connection error - user doesn't know that he is disconnected first so it is better to say this as the function will return false and stop other functions
if(manual!=true)
{
$('#chatTextDiv').append('You could not be connected. Please try again later.<hr/>');
//Stop getting messages
clearInterval(setintervalid);
callback(false);
}
elseif(manual==true)
{
$('#chatTextDiv').append('You could not be disconnected. Please try again later.<hr/>');
callback(true);
}
});
}

closeConnection(manual, function(success) {
//Process result
});

关于jquery函数返回不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523413/

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