2013-05-12 51 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

相关问题