【问题标题】:Automatic store values in a json file [duplicate]自动将值存储在 json 文件中 [重复]
【发布时间】:2021-01-11 23:35:40
【问题描述】:

我有一个名为 jsondb.json 的 JSON 文件,我还有一个名为 index.html 的文件,在 index.html 中我有一个输入标签和一个按钮。 所以我希望当我在输入标签中写一些东西然后单击按钮时,输入的值将保存在我的 json 文件中。

索引.HTML

<input placeholder='txt' id='txt' />

<button>save</button>

JSON 文件

{"txt":""}

【问题讨论】:

  • 您将如何编辑 JSON 文件?我会用 PHP 来做。

标签: javascript html arrays json


【解决方案1】:

您需要将inputbutton 包装在带有action 属性和method 属性的form 标记中(假设您在php 中)。 action 属性是指处理结果的页面,method 属性是用于将表单数据发送到服务器的操作。 在您的操作页面中,您需要使用$_GET[param]$_POST[param] 获取从您的页面发送的参数,具体取决于您的method 属性的值。 然后你可以用 PHP 中的json_encode 函数将值写入文件

例如:

index.php(注意.php)

    <form action='somepage.php' method='GET'>
        <input type="text" name="text" placeholder="txt">
        <button type="submit">Save<button>
    </form>

somepage.php

    //get the results
    $txt=$_GET['text']
    $array = ["text"=>$txt]
    
    //write the result in a text file
    $json = json_encode($array)
    $file=fopen('jsondb.json')
    fwrite($file,$json)
    fclose($file)

【讨论】:

  • 什么意思?
  • yourfile.txt 更改为jsondb.json
  • 所以不能,只有 JavaScript 能做到这一点???,我只想用 JavaScript
  • 如果你只需要 javascript,你可以使用 nodejs 后端。无论如何,您都需要一个后端来处理请求并写入文件。
  • 不工作,
【解决方案2】:

嗯,这个答案需要 PHP,但假设你有一个 Web 服务器,这就是我的答案:

var object = {
  txt : ""
}
function save(){
  var txt = $("#txt").text();
  object.txt = txt;
  savetofile(JSON.stringify(object));
}
function savetofile(txt){
         $.ajax({
               type: "POST",
               url: "process.php",
               data: {  
                        'file': txt
                 },
            });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input placeholder='txt' id='txt' />

<button onClick="save()">save</button>

process.php:

<?php
file_put_contents("jsondb.json", $_POST["file"]);
?>

【讨论】:

  • 所以不能,只有 JavaScript 能做到这一点???,我只想用 JavaScript
  • Javascript 是客户端。客户端意味着客户端(也就是用户)执行脚本。要在服务器上编辑文件,您需要一个后端脚本。 PHP 和我的方式使用更多的 javascript 和更少的 PHP。
  • 您可以使用nodejs.org 仅在需要时使用javascript。
猜你喜欢
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-30
  • 1970-01-01
  • 2018-05-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多