jquery - ajax 查询不等待第一个 ajax 查询执行——我认为
问题描述
我有两个 ajax 查询。在第一个中,我输入了一条新记录,显示了一件艺术品以及用户对其的评分和评论。在第二个中,我查看所有记录,确定每个不同艺术家的响应数量和平均比率,并在网页上显示这些数字。
问题是,当输入新记录时,页面反馈并不总是能识别出新记录已被输入。如果您刷新页面,用户响应的数量将增加 1,并反映新的平均值。所以我认为我处理jquery的异步方面的方式有些不对劲。
谁能告诉我我做错了什么?
//code about that gets the user's answers from a form
//then the code below
function ajax1() { //put in database
$.ajax({
url: "php/newComment.php",
method: "POST",
data: ({
'artwork': artwork,
'ip': ip,
'timestamp': timestamp,
'rank': rank,
'comment': comment
}),
success: function(data) {},
error: function(jxhr, statusText, err) {}
});
} //all good here; it works
$.when(ajax1()).done(function() {
$.ajax({ //fetch the number of responses
//and average data from dB
url: "php/get-averages-number.php",
method: "POST",
data: ({
'artwork': artwork
}),
success: function(data) {
var objArt = jQuery.parseJSON(data);
for (i = 0; i < objArt.length; i++) {
if (artwork == objArt[i].artwork) {
$('#' + artwork + '-respondents').text(objArt[i].num + " respondent(s) so far");
var score = parseFloat(objArt[i].avg);
var rounded = Math.round(score * 10) / 10;
$('#' + artwork + '-average').text(rounded.toFixed(1) + " average score");
}
}
},
error: function(jxhr, statusText, err) {}
}); //this works, but doesn't always reflect that
//a new response was just entered
});
解决方案
The issue is because your ajax1()
function is not returning a promise (or indeed, anything at all) so done()
fires immediately.
To fix this, return the jqXHR object from $.ajax()
in ajax1()
to the $.when()
call by adding the return
keyword:
function ajax1() {
return $.ajax({ // add return here
// ajax settings...
});
}
推荐阅读
- c# - 确保特定异常始终导致给定的 HTTP 响应状态代码
- structured-text - 如何在结构化文本中将 memcpy 转换为二维数组?
- python - 使用 boto3 从 S3 下载大文本文件
- amazon-ec2 - 即使手动将公钥添加到 authorized_keys 也无法连接到 AWS 实例
- javascript - 无法使用 pinterest js SDK 通过 javascript 创建 pinterest pin
- c# - 在指定路径中找不到项目
- asp.net - 如何忽略包含 aspx 中的错误“未声明 var。由于其保护级别,它可能无法访问。”
- java - java.lang.ClassCastException: java.math.BigInteger 不能用 sql 和 java 转换为 java.lang.Long Spring
- teamsql - 为什么团队 sql 运行查询这么慢?
- ionic-view - 离子图标的条件外观