尝试保存到文件JSON字符串并从中读取时出错

时间:2021-07-22 22:41:34

I have put together the following increment counter and have it running on a page:

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

<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>

With this PHP file:

有了这个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;
?>

The idea being there are 2 or more independent counters on the page, that both work independently of each other, and the txt file generated on the server keeps tracks of the values. E.g.

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

button 1: 4
button 2: 8

按钮1:4按钮2:8

However, when I try to use it, I receive the following error:

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

PHP Notice: Undefined variable: json in increase_counter.php on line 2"

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

I am very new to Javascript/PHP and have been working on it the past two days but have not been able to figure out how to make it work!
What's missing?

我是Javascript / PHP的新手,过去两天一直在研究它,但一直无法弄清楚如何让它工作!少了什么东西?

2 个解决方案

#1


0  

OP's code uses $json (line 2) before setting it then sets $json (line 8) but never uses it. Below is sample code that'll save all counters in a single file. The counters are stored in JSON format in the file.

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];
}

EDIT: Added TRUE to json_decode (I always seem to forget that :( ) and checked for null/bad-json.

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

#2


0  

You can add in you code php this:

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

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

On html i suggest you change the id elements to button_1 and button_2, like:

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

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

#1


0  

OP's code uses $json (line 2) before setting it then sets $json (line 8) but never uses it. Below is sample code that'll save all counters in a single file. The counters are stored in JSON format in the file.

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];
}

EDIT: Added TRUE to json_decode (I always seem to forget that :( ) and checked for null/bad-json.

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

#2


0  

You can add in you code php this:

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

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

On html i suggest you change the id elements to button_1 and button_2, like:

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

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