【问题标题】:Jquery function doesn't wait result of Javascript function result why? [duplicate]为什么jQuery函数不等待Javascript函数结果的结果? [复制]
【发布时间】:2013-05-12 13:43:11
【问题描述】:

我有两种方法。第二个调用第一个。当我将警报函数放入第一个函数时,我可以看到返回值。但第二个函数将值视为未定义。我不明白为什么 2. 无法处理价值?

function getTweetReply(id_str) {
    $.getJSON("get_tweet_reply.php", {id_str: id_str}, function(json) {
      tweet_relpy = '<blockquote>'+json.results[0].text+'</blockquote>';
      alert(tweet_relpy); // --> I can see the result
      return tweet_relpy;
    });
}

$(document).on("click", ".tweet",function(){
    var id_str = $(this).attr("id");
    $.getJSON("get_tweet_details.php", {id_str: id_str},     function(json) {
        tweet = '<img src="'+json.results[0].profile_image_url+'"><br>\
                ' + json.results[0].from_user + '<br>\
                ' + json.results[0].from_user_name + '<br>\
                ' + getTweetReply(json.results[0].id_str) + '</b><br>'; // --> undefined
       $("#float").html('<div id="replybox">'+ tweet +'</div>');
    });
});

【问题讨论】:

  • 你可能会看到结果,但是 return 值被忽略了,因为回调是通过事件循环异步调用的,而不是通过原始调用函数。
  • 谢谢,但我在这里找不到答案。我有 2 个 getJSON 函数。 $(float).html 必须等待 getTweetReply 中的第一个
  • 在“详细信息”查询中发送的id_str 是否与发送到“获取回复”查询的 ID 相同?
  • 一些可能对您有所帮助的背景资料:html5rocks.com/en/tutorials/async/deferred

标签: javascript jquery ajax function asynchronous


【解决方案1】:

首先,将 AJAX 与内容生成分开,并公开 Promise:

function getTweetDetails(id_str) {
    return $.getJSON("get_tweet_details.php", {id_str: id_str});
}

function getTweetReply(id_str) {
    return $.getJSON("get_tweet_reply.php", {id_str: id_str});
}

function render(details, reply) {
    // render HTML based on "details" and "reply" JSON structures
    var tweet = '...';
    $("#float").html('<div id="replybox">'+ tweet +'</div>');
}

这是关注点分离 - 这两个 AJAX 相关函数现在不需要回调参数,返回的“承诺”允许任意数量的回调取决于结果,并且还用于$.getJSON() 不直接支持的错误回调工作。

那么,由于第二个查询依赖于第一个:

$(document).on("click", ".tweet", function() {
    var id_str = this.id; // not $(this).attr('id') !!
    getTweetDetails(id_str).done(function(details) {
        getTweetReply(details.results[0].id_str).done(function(reply) {
            render(details, reply);
        });
    });
});

【讨论】:

  • 非常感谢阿妮卡。没有第一个 id 是原始推文的 id,第二个是 reply_tweet 的 id。具有回调()函数的先前答案解决了问题
  • 我之前没用过渲染功能。我现在就学。谢谢
  • @OzanDikerler 我代码中的第二个块适用于回复 ID 取决于第一个 ID 的情况。您必须自己编写 render 函数。我只是想演示如何(并且应该)将 AJAX 功能与将结果转换为 HTML 的代码分开。
  • @OzanDikerler 好的,我的答案稍微更完整了——我现在的提议应该更明显了
  • 其实我很喜欢你的回答,因为它还清楚地说明了 done 的同步堆叠和 when 和 done 的异步使用......即使这样它是一个很好的阅读示例:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 2019-12-08
  • 1970-01-01
相关资源
最近更新 更多