我使用ajax,php和json来存储json文件中的点击次数......让我们说文件是这样的:
count.json
{"countbtn1":28,"countbtn2":25,"countbtn3":39}
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "count.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
我需要在页面加载中将每个btn值放在这些值中:
<div class='smallbtn1'>0</div>
<div class='smallbtn2'>0</div>
<div class='smallbtn3'>0</div>
使用以下方法计算和更新json文件:
$('.download').click(function() {
//get name of button
var name= $(this).prop('name');
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
}
}
});
return true;
});
..我尝试用以下内容更新页面加载计数:
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
...但在第一次点击后,它不会在加载时更新值。
PS:整件事包裹在$(document).ready(function(){..});
答案 0 :(得分:2)
在看到服务器上的代码后,我说问题是你如何调用AJAX。你这样做:
$(document).ready(function(){
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
但是你还没有定义name
是什么(它是在click事件中定义的,但是在第一次加载页面时没有定义)。你应该这样做:
$(".download").each(function() {
var name = $(this).attr("name");
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name },
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
});
因此,为每个按钮调用AJAX,并通过name
使用属性$(this).attr("name")
。
答案 1 :(得分:0)
尝试使用$(document).ready()
完全加载页面后发送AJAX请求:
$(document).ready(function() {
$.ajax({
url: "downloadsCount.php",
data: { buttonName:name },
async: false,
method: "POST",
success: function(response) {
$('.small' + name).html(response);
}
});
});