尝试保存到文件JSON字符串

时间:2016-12-11 03:10:31

标签: javascript php json

我已将以下增量计数器放在一起并让它在页面上运行:

<html>
<head>
<meta charset="utf-8">
<title>Click Counter</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
    document.write(unescape("%3Cscript src='inc/js/jquery-1.11.2.min.js' type='text/javascript'%3E%3C/script%3E"));
}
</script>
<script type="text/javascript">
$(function(){
$('body').on('click', 'button', function(event){
    event.preventDefault();
    var currentNumber = $('#currentNumber').text();
    $.ajax({
        method: 'POST',
        url: 'increase_counter.php',
        data: {
counterId: event.target.id,
value: currentNumber
}
    })
    .done(function(newNumber){
        $('#currentNumber').text(newNumber);
        });
    });
});
</script>
</head>
<body>
<div id="currentNumber">[xyz-ips snippet="Counter"]</div>
<button type="button" id="button 1">First Counter</button>
<button type="button" id="button 2">Second Counter</button>
</body>
</html>

使用这个PHP文件:

<?php
$counters = json_decode($json);
if (isset($_POST['counterId'])) {
    $counterId = filter_input(INPUT_POST, 'counterId', FILTER_SANITIZE_STRING);
    $value = filter_input(INPUT_POST, 'value', FILTER_VALIDATE_INT);
    $counters[$counterId] = $value;
}
$json = json_encode($counters);
$counter_name = 'emailCounter.txt';

if (!file_exists($counter_name)) {
    $f = fopen($counter_name, "w");
    fwrite($f,"0");
    fclose($f);
}

$counterVal = file_get_contents($counter_name);
$counterVal++;

$f = fopen($counter_name,"w");
fwrite($f, $counterVal);
fclose($f);

echo $counterVal;
?>

这个想法在页面上有两个或更多的独立计数器,它们彼此独立工作,并且在服务器上生成的txt文件保持值的轨迹。例如。

  

按钮1:4
  按钮2:8

但是,当我尝试使用它时,收到以下错误:

  

PHP注意:未定义的变量:第2行的increase_counter.php中的json“

我是Javascript / PHP的新手,并且在过去的两天里一直在研究它,但是还没弄清楚如何让它工作!
有什么遗漏?

2 个答案:

答案 0 :(得分:0)

OP的代码在设置之前使用$json(第2行),然后设置$json(第8行)但从不使用它。下面是将所有计数器保存在单个文件中的示例代码。计数器以JSON格式存储在文件中。

$countersFile = 'emailCounter.txt';

if ( isset($_POST['counterId']) ) {
    $counterId = $_POST['counterId'];

    if ( !file_exists($countersFile) ) {
        $counters = [];
    } else {
        $counters = json_decode(file_get_contents($countersFile), TRUE);
        if ( is_null($counters) ) $counters = [];
    }

    if ( array_key_exists($counterId, $counters) ) {
        $counters[$counterId]++;
    } else {
        $counters[$counterId] = 1;
    }

    file_put_contents($countersFile,
        json_encode($counters, JSON_PRETTY_PRINT),
        LOCK_EX);

    echo $counters[$counterId];
}

编辑:为json_decode添加了TRUE(我似乎总是忘记:()并检查null / bad-json。

答案 1 :(得分:0)

你可以在这里添加代码php:

<?php
$json = '';
if (file_exists('emailCounter.txt') {
  $json = file_get_contents('emailCounter.txt');
}
$counters = json_decode($json); // your old line 2
// ... 
?>

在html上我建议你将id元素更改为button_1和button_2,如:

<button type="button" id="button_1">First Counter</button>
<button type="button" id="button_2">Second Counter</button>