Ajax成功的动作

时间:2016-12-11 02:04:24

标签: javascript jquery ajax

当有人点击“喜欢”按钮时,我正在检查数据库是否已经被这个人所喜欢。我正在使用ajax来检查这个。

当照片已经被喜欢时,成功消息说“已经喜欢”,否则它是空字符串。

问题在于增加“当前喜欢”并不起作用。我尝试使用警报来查看数字,它始终显示第一行中的第一个数字,而不会增加currentLikes++

实际上会发生什么?我全局定义了变量。

var currentLikes = $(this).next('span').text(); 

$.ajax({
    type: "POST",
    url: "/save_like",
    success: function(msg){
        addLike(msg);
    }
}); 

function addLike(msg){
    if(msg !== 'already liked'){
        currentLikes++;
    }
alert(currentLikes); 
$(this).next('span').html(currentLikes);
}

3 个答案:

答案 0 :(得分:2)

currentLikes = currentLikes++;替换为currentLikes++;

并将$(this).next('span').html(currentLikes);放入addLike函数

答案 1 :(得分:1)

alert(currentLikes);$(this).next('span').html(currentLikes);不在您的AJAX代码中,并且将在AJAX调用完成之前执行。将该代码移到addLike函数中以查看正确的值。

另外,将currentLikes = currentLikes++代码更改为currentLikes++,因为++位于表达式的末尾,因此它是“后递增”运算符,这意味着值在当前声明完成评估之后才会增加。如果您编写了currentLikes = ++currentLikes并使用了“预增量”运算符,则在评估表达式的其余部分之前,该值将会增加并且可以正常工作,但只需说currentLikes++(无需重新分配给currenLikes更好 - 它将值上升并将其存储在当前变量中。

此外,this将不会在回调中引用您想要它的元素,因为this在JavaScript中是易变的 - 它的对象绑定更改取决于调用包含它的代码的方式,所以你需要更新,这将是一个正确的参考。如果保存对要使用的元素的引用(而不是该元素的属性),则可以稍后使用该变量引用该元素。

此外,您正在从span获取原始数据,并且会以字符串形式返回给您,您应该在使用它之前将其转换为数字。

最后,确认msg实际上没有返回'already liked' EXACTLY AS YOU HAVE IT IN QUOTES. Remember, strings are literals and they are case-sensitive. If there's even an extra space in msg`,您的代码将无法正常运行。

// Store a reference to the likes element (not any property value of it)
var currentLikeElement = $(this).next('span'); 

// Now, get the old like count out of the DOM and convert to a number
var likeCount = parseInt(currentLikeElement.text(), 10);

alert(likeCount);

$.ajax({
    type: "POST",
    url: "/save_like",
    success: function(msg){
        // Let's make sure msg is cleaned up and ready for comparison
        // by trimming any leading or trailing spaces off of it and forcing
        // it to all lower-case (because we'll be comparing it to lower-
        // case later).
        msg = msg.trim().toLowerCase();
        addLike(msg);
    }
}); 

function addLike(msg){
  console.log(msg);  // <--  What does this return?
  if(msg !== 'already liked'){
        likeCount++;
  }
  alert(likeCount); 

  // Inject the new like count into the stored object reference:
  currentLikeElement.text(likeCount);
}

答案 2 :(得分:0)

根据您的示例代码,尝试将您的计数更新脚本放在 addLike(msg)函数中。

function addLike(msg){
  if(msg !== 'already liked'){
    currentLikes++;
    $(this).next('span').html(currentLikes);
  }
}