首页 > 解决方案 > 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
});

标签: jqueryajaxasynchronous

解决方案


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

推荐阅读