2011-11-09 38 views
0

好的,所以我有一個按鈕,點擊後會改變給定div的類。事情是,我只想在變量(回答)不包含字符串「No」的情況下發生這種情況。這有效......但問題是,即使變量不包含單詞「否」,代碼也不會執行。 ajax結果包含「無用戶ID」或「用戶ID:#」。如果變量包含字符串,jQuery會執行

$(document).ready(function() { 

$('.like').on('click', function() { 
    postID = $(this).attr('id').replace('like_', ''); 

    // Declare variables 
    value = '1'; 

    myajax(); 

    return false; 

    var doit = answer.IndexOf("No"); 
    if (doit < 0){ 
     $('#post_' + postID).removeClass('dislike').addClass('like'); 
    } 

}); 

function myajax(){ 
    // Send values to database 
    $.ajax({ 
     url: 'check.php', 
     //check.php receives the values sent to it and stores them in the database 
     type: 'POST', 
     data: 'postID=' + postID + '&value=' + value, 
     success: function(result) { 
      answer = result; 
      $('#Message_' + postID).html('').html(result).prependTo('#post_' + postID); 
     } 
    }); 
} 
}); 

因此我知道我的問題在於var doit。我只是無法弄清楚它有什麼問題。

回答

3

success函數調用myajax回報

第一「一」在AJAX表示異步的,所以你要整個代碼塊移動到成功的功能後執行,likeso:

$(document).ready(function() { 

$('.like').on('click', function() { 
    postID = $(this).attr('id').replace('like_', ''); 

    // Declare variables 
    value = '1'; 

    myajax(function(answer) { 
      if (answer.indexOf("No") < 0){ 
       $('#post_' + postID).removeClass('dislike').addClass('like'); 
      } 
    }); 

    return false; 

}); 

    $('.dontlike').click(function() { 
    myajax(function(answer) { alert('check.php returned:' + answer); } 
    }); 

function myajax(onSuccess){ 
    // Send values to database 
    $.ajax({ 
     url: 'check.php', 
     //check.php receives the values sent to it and stores them in the database 
     type: 'POST', 
     data: 'postID=' + postID + '&value=' + value, 
     success: function(result) { 
      $('#Message_' + postID).html('').html(result).prependTo('#post_' + postID); 
      onSuccess(result); 
     } 
    }); 
} 
}); 
+0

雖然'var answer = result;'會更好嗎?或者只是'result.indexOf(「否」)'?另外我認爲它是'indexOf'中的小寫'i'。 –

+0

是和是,已更新 – Jason

+0

此解決方案不起作用。 ajax存在一個功能的原因。我有另一個按鈕(不喜歡),它也執行相同的功能,但設置不同的變量。如果我把indexOf放在我的ajax中,它不會區分哪個按鈕被點擊。 – Sweepster

相關問題