0

私は2つの方法を持っています。2 番目のものは最初のものを呼び出します。アラート関数を最初の関数に入れると、戻り値が表示されます。しかし、2 番目の関数では値が未定義と見なされます。なぜ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>');
    });
});
4

1 に答える 1

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>');
}

これは問題の分離です。2 つの AJAX 関連関数はコールバック パラメータを必要としなくなりました。返される「約束」により、結果に依存する任意の数のコールバックが許可されます$.getJSON()。仕事。

次に、2 番目のクエリは最初のクエリに依存するため、次のようになります。

$(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);
        });
    });
});
于 2013-05-12T13:59:15.480 に答える