我在Ajax上爲用戶評論創建了一個簡單的投票系統(+和 - )。一頁有50條發表評論,您可以爲每個「加號」或「減號」投票。這些數據通過PHP腳本發送到數據庫。但是,如果用戶投票,則PHP腳本被調用50次 - 它在Chrome開發人員工具中可見。有錯誤 - 比預期更多的價值。這是我的代碼(兩個DIV按鈕和腳本)。如何防止多個加載PHP腳本調用JS腳本?
請告訴我如何將代碼更改爲腳本(up_vote.php或down_vote.php)只調用一次。
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
//php code below;
echo "<div class=\"box1\"><div class=\"up\"><a href=\"#\" class=\"vote\" title=\"+ 1\" alt=\"+ 1\" id=".$row["id"]." name=\"up\">".$up."</a></div>"
."<div class=\"down\"><a href=\"#\" class=\"vote\" title=\"- 1\" alt=\"- 1\" id=".$row["id"]." name=\"down\">".$down."</a></div></div>\n";
不能重現:http://jsfiddle.net/jxUKN/有沒有其他的js代碼,你正在省略? – Mahn
或者你是否通過ajax加載每個人的評論? – Mahn
我通過PHP加載所有評論。id同樣的兩個按鈕,但不同的所有評論 – Astraport