Jquery函数不等待Javascript函数的结果为什么?
Jquery function doesn't wait result of Javascript function result why?
我有两个方法。第二个呼叫第一个。当我将一个警报函数放入第一个函数中时,我可以看到返回值。但是第二个函数认为值是未定义的。我不明白为什么。一个人不能处理这个值?
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>');
});
});
首先,将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);
});
});
});
相关文章:
- JScript 错误: 无法分配给函数结果
- 显示基于javascript函数结果的HTML代码
- 访问来自另一个函数的函数结果
- 将函数结果传递给Javascript中的另一个函数变量
- NaN作为函数结果而不是必需的整数出现问题
- 更改javascript更改函数结果的颜色
- 从函数结果中检测三角函数
- 根据函数结果使用 JavaScript 更改图像
- 如何返回函数结果并将它们设置为标记的内部 HTML
- JavaScript 如何将函数结果与数组中的值一起传递到同一个函数中
- 用
标记包装 JQuery 函数结果
- 节点函数结果未定义
- 使用Cheerio和Response for Node web scraper,将响应函数结果传递给视图
- 在所有项目javascript中显示函数结果
- 平板电脑友好的悬停工具提示,显示基于javascript函数结果的动态文本
- 在机器时间更改后立即更新Date()函数结果
- 屈服函数结果
- 如何在JavaScript中处理异步函数结果
- 声明和定义全局变量作为函数结果有时有效
- Jquery&函数结果,作为属性名称