2013-05-12 71 views
0

我有2種方法。第二個叫第一個。當我把一個警報函數放入第一個函數時,我可以看到返回值。但第二個函數將該值視爲未定義。我無法理解爲什麼2.一個人無法處理價值?jquery函數不等Javascript結果的結果爲什麼?

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

你很可能是能夠看到的結果,但'return'價值越來越被忽略,因爲回調是通過事件循環異步調用,而不是通過原始的調用函數。 – Alnitak 2013-05-12 13:49:58

+0

謝謝,但我無法在這裏找到答案。我有2 getJSON函數。 $(float).html必須等待getTweetReply中的第一個 – 2013-05-12 13:53:31

+0

是在「details」查詢中發送的'id_str'查詢與發送給「get reply」查詢的ID相同的ID嗎? – Alnitak 2013-05-12 13:57:56

回答

1

首先,從內容生成單獨的AJAX,並公開承諾:

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); 
     }); 
    }); 
}); 
+0

非常感謝您Alnika。沒有第一個id是原來的tweet的id,第二個是reply_tweet的id。具有回調()函數的上一個答案解決了問題 – 2013-05-12 14:07:30

+0

我之前沒有使用渲染函數。我現在就學會它。謝謝 – 2013-05-12 14:08:25

+0

@OzanDikerler我的代碼中的第二個塊適用於應答ID取決於第一個ID的情況。你必須自己編寫'render'函數。我只是試圖演示如何(應該)將AJAX功能與將結果轉換爲HTML的代碼分開。 – Alnitak 2013-05-12 14:09:19