簡體   English   中英

如何通過 html、json 和 php 中的輸入帖子添加到列表?(不使用數據庫)?

[英]How do i add to a list via an input Post in html, json, and php?(without using a database)?

我已經為此苦苦掙扎了一段時間。 我認為我的邏輯中有一個缺失的部分,我無法弄清楚它是什么。 我正在嘗試使用 Html、json 和 php 制作待辦事項應用程序。 如何將輸入值存儲為數組,然后作為待辦事項列表回顯?

<form method="POST" action="TodoAppChallenge.php">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text"  id ="wordsGoHere" name="wordsGoHere">
    </p>
    <input type="submit" name="pressHere" value="           add Your Task               ">
</form>
<?php
include('TodoAppChallengeExtra.php');
?>

<table>
      <thead>
      <th>Your Tasks</th>
      </thead>
      <tbody>
<?php
    if(isset($_POST['pressHere'])){
                  
            $wordsGoHere = array(
            'wordsGoHere' => $_POST['wordsGoHere'],
      );    //i think my mistake is somewhere around here
            array_push($wordsGoHere,$_POST['wordsGoHere']);
            $data = $wordsGoHere;
            $data = json_encode($data, JSON_PRETTY_PRINT);
            file_put_contents('extra.json', $data);
            $data = file_get_contents('extra.json');
            $data = json_decode($data);
            foreach($data as $row){
            echo "
                  <tr>
                        <td>
                        <ul><li>".$row->$data."</li></ul>
                        </td>
                  </tr>
            ";
    }} else {
      echo 'add a Task';
     }
      ?>
       </tbody>
 </table>

代碼已注釋,但要點如下:

  • 將表單處理上移以避免“標題已發送...”錯誤
  • 開啟錯誤報告
  • 使用理智的、通俗易懂的變量名
  • 讓您的 arrays 盡可能簡單

您還可以做些什么來改進? 使用常量來定義諸如 session key todo ,驗證之類的東西,將其拆分為處理文件和演示文件。

如果你想 go 更高級一點,設計一個存儲機制,你的表單和表單處理邏輯不知道或不關心數據是否存儲在 JSON 文件、Z21D6F40CFB511982E4424E0E250 或其他文件中。 它看起來像: $storage->save($userInput); $storage->retrieve();

祝你好運!

通過 session 實現。

<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Always do these 2 things on every request.

// 1. Start your session
session_start();

// 2. Initialize the session array if it hasn't been initialized already.
// This only happens once per session.
if (!isset($_SESSION['todo'])) {
    $_SESSION['todo'] = [];
}

// Now you are free to start writing and reading from your session.

// Check if the request is coming in via POST.
// Do your processing up top above your HTML otherwise you can run into "Headers already sent..." errors.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // This is what the user typed in.
    $input = $_POST['wordsGoHere'];

    // @todo do your validation here.

    // Put the user's input in the session.
    $_SESSION['todo'][] = $input;
}

// Finally, read out the contents from your session so your form has access to it.
$dataFromSession = $_SESSION['todo'];
?>

<form method="POST">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text" id="wordsGoHere" name="wordsGoHere">
    </p>

    <input type="submit" name="submit" value="Add Your Task">
</form>
<table>
    <thead>
    <tr>
        <th>
            Your Tasks
        </th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($dataFromSession as $item): ?>

        <tr>
            <td>
                <?= $item; ?>
            </td>
        </tr>

    <? endforeach; ?>
    </tbody>
</table>

通過 JSON 文件實現。

<?php

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Initialize your JSON file by ensuring the file actually exists. If it doesn't, create an empty file.
if (!file_exists('extra.json')) {
    file_put_contents('extra.json', '[]');
}

// Now you are free to start writing and reading from your JSON file.

// Check if the request is coming in via POST.
// Do your processing up top above your HTML otherwise you can run into "Headers already sent..." errors.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // This is what the user typed in.
    $input = $_POST['wordsGoHere'];

    // @todo do your validation here.

    // Read the current state of the file.
    $contents = file_get_contents('extra.json');
    $dataFromFile = json_decode($contents, true);

    // Push the new value on the end of the array.
    $dataFromFile[] = $input;

    // Write the array back to the file.
    $json = json_encode($dataFromFile, JSON_PRETTY_PRINT);
    file_put_contents('extra.json', $json);
}

// Finally, read out the latest contents from your file so your form has access to it.
$contents = file_get_contents('extra.json');
$dataFromFile = json_decode($contents, true);
?>

<form method="POST">
    <p>
        <label for="wordsGoHere">type your task here</label>
        <input type="text" id="wordsGoHere" name="wordsGoHere">
    </p>

    <input type="submit" name="submit" value="Add Your Task">
</form>
<table>
    <thead>
    <tr>
        <th>
            Your Tasks
        </th>
    </tr>
    </thead>

    <tbody>
    <?php foreach ($dataFromFile as $item): ?>

        <tr>
            <td>
                <?= $item; ?>
            </td>
        </tr>

    <? endforeach; ?>
    </tbody>
</table>

我試圖讓這更簡單,你有很多你不需要的變量重新分配。 基本上

  if(isset($_POST['pressHere'])){
   // get the tasks, note the 'true' flag on the json decode so you have an array rather than an object

    $tasks = json_decode(file_get_contents('extra.json'), true);
    
    //keep things simple - use the same array and just add the new value to it

    $tasks[] = $_POST['wordsGoHere'];

    //print out your values
    foreach($tasks as $task){
        echo "
              <tr>
                    <td>
                    <ul><li>" . $task . "</li></ul>
                    </td>
              </tr>
        ";
    }

    //using the same array prepare to save it
    $tasks = json_encode($tasks, JSON_PRETTY_PRINT);

    //save the data
    file_put_contents('extra.json', $tasks);


} else {
    echo 'add a Task';

}

它更易於閱讀,易於理解,有意義並且(重要)有效

//EDIT 值得一說,我只是按照你的邏輯在這里,所以列表只在你發布它時顯示,如果你希望它一直顯示你只需要稍微改變這樣的邏輯:

$tasks = json_decode(file_get_contents('extra.json'), true);

if(isset($_POST['pressHere'])) {
    $tasks[] = $_POST['wordsGoHere'];
}

if(count($tasks) > 0) {
    foreach($tasks ....
    ....
} else {
    echo 'add a Task';

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM