Получить содержимое файла json при загрузке страницы



Я использую ajax, php и json для хранения количества кликов в файле json...Допустим, файл выглядит так:




Граф.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] ;
?>



Загрузки.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 внутри них на странице load:




<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(){..});

586   2  

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").

Попробуйте отправить запрос AJAX после полной загрузки страницы с помощью $(document).ready():

$(document).ready(function() {
    $.ajax({ 
        url: "downloadsCount.php", 
        data: { buttonName:name }, 
        async: false,
        method: "POST", 
        success: function(response) { 
            $('.small' + name).html(response);
        } 
    });
});

Comments

    Ничего не найдено.