来自函数的返回对象在 jQuery 中未从 $.post 定义

return object from function is undefined from $.post in jquery

本文关键字:定义 post jQuery 函数 返回 对象      更新时间:2023-09-26

我有一个jquery post函数,它从php代码块返回一个数据对象。

$.post("get_chat_history.php", {
    item_id : item_id,
    participant_1 : participant_1,
    participant_2 : participant_2
}, function(data) {
    alert(data);
    return data;
});

这是从另一个JavaScript文件中的以下函数调用的

var data = getChatHistory(current_member_id,item_global["user"]    ["member_id"],item_global["id"]);
alert(data);

现在在 $.post 中,alert(data) 以 JSON 格式抛出正确的值,但是当我测试返回给调用函数的相同值时,我变得未定义。

我是否缺少一些东西,因为我想保持这个函数的通用性和可从其他地方调用?

问候

萨帕托斯

这是因为此函数运行异步电子并将数据返回到匿名函数function(data) {}。使用回调。

下面是示例:

function getFoo(callback){
    $.get('somepage.html', function(data){
        callback(data)
    })
}
getFoo(function (data){
     // do something with data
})​

您面临的问题是 jQuery.post 是异步的。当getChatHistory被调用时,它还没有收到来自服务器的回复,所以它undefined

为此,我将getChatHistory实现为一个函数,该函数获取您需要传递给服务器的数据,以及触发"成功"部分时执行的函数。

有关回调的更多信息。