我正在使用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(){..});
在看到服务器上的代码之后,我要说的问题是您如何调用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")
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句