我使用ajax、php和json将点击次数存储在json文件中。。。假设文件是这样的:
count.json
{"countbtn1":28,"countbtn2":25,"countbtn3":39}
下载Compunt.php
<?php
$buttonName=$_POST["buttonName"];
$file = "count.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
下载s.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(){..});
中
在看到服务器上的代码后,我认为问题在于如何调用AJAX。你正在这样做:
$(document).ready(function(){
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
但是您还没有定义什么是name
(它是在点击事件中定义的,但不是在第一次加载页面时定义的)。你应该这样做:
$(".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,并通过执行$(this).attr("name")
来使用属性name
。
使用$(document).ready()
:在页面完全加载后尝试发送AJAX请求
$(document).ready(function() {
$.ajax({
url: "downloadsCount.php",
data: { buttonName:name },
async: false,
method: "POST",
success: function(response) {
$('.small' + name).html(response);
}
});
});