我的代码有问题,它就像一个按钮。它显示了喜欢的数量。如果用户尚未投票(cookie),他可以点击并反击增加。问题是计数器在第一次点击时没有更新(如果我停用cookie检查并多次投票),下次刷新就会更新所有内容。似乎在插入后端之前发生了一些计数。我想probem是在JavaScript中,ajax post cross domain可以工作,但是会出错,这就是为什么“error:setCookieAndUpdateButton()”
这是我的前端代码:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div><a id="like_button" href="#">Like</a></div>
<script>
var url = "http://thumbs-up.some-server.com/";
var appName = "next_test";
document.write("<script src=\"" + url + "jquery.cookie.js\"><\/script>");
$(document).ready(function(){
updateButton();
$("#like_button").click(function(){
if ($.cookie(appName + "_voted") == "true") {return;}
$.ajax({
type: "POST",
dataType: "json",
crossDomain: true,
url: url + "increase_counter.php",
data: {referrer: appName},
success: setCookieAndUpdateButton(),
error: setCookieAndUpdateButton()
});
});
});
function setCookieAndUpdateButton()
{
updateButton();
$.cookie(appName + "_voted", "true", {expires: 20*365});
}
function updateButton()
{
$.ajax({
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonpCallback: 'callback4jquery',
url: url + "get_counter_for_referrer.php",
data: {referrer: appName},
success: function (json) {
if ($.cookie(appName + "_voted") != "true"){
$("#like_button").html("<a id=\"like_button\" href=\"#\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</a>")
}
else{
$("#like_button").html("<span id=\"like_button\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</span>");
$('#like_button').unbind('click');
}
}
});
}
</script>
答案 0 :(得分:2)
在第一个ajax调用中更改代码如下:
success: setCookieAndUpdateButton,
error: setCookieAndUpdateButton
两个都没有()