【问题标题】:Add user to a Json list #PHP #JS将用户添加到 Json 列表 #PHP #JS
【发布时间】:2017-07-07 14:27:51
【问题描述】:

我们正在尝试从前端表单向 Json 文件添加一些新用户。

我们通过 Js 传递从表单中获取的代码,然后我们尝试(通过 PHP)将用户插入的值传递到 json 文件中。

从 HTML 中提取

  <div class="log">
                    <p>Username Nuovo Utente</p>
                    <input class="nome" id="nuovoUtente" placeholder="inserisci il nome"><br>
                    <p>Password Password Nuovo Utente</p>
                    <input type="password" id="nuovaPsw" class="psw"> <br>
                    <button type="submit" class="lo" id="aggiunto">Aggiungi Nuovo Utente</button>
                </div>

从js文件中提取

 let newNom = document.getElementById('nuovoUtente');
   let newPass = document.getElementById('nuovaPsw');

   aggiunto.onclick=function(){
       $.get("utenti.php", { nome: newNom.value , pw: newPass.value });
   }

php 文件

  <?php
    $data[] = $_GET['data'];
    console.log($data[]);
    $inp = file_get_contents('pindex.json');
    $tempArray = json_decode($inp);
    array_push($tempArray, $data);
    $jsonData = json_encode($tempArray);
    file_put_contents('pindex.json', $jsonData);
    ?>

【问题讨论】:

  • 问题/问题是什么?
  • '$.get("utenti.php", { nome: newNom.value , pw: newPass.value });` 为了您自己和他人的安全,请不要 i> 通过 GET 发送密码
  • 这些是标签吗?

标签: javascript php jquery json


【解决方案1】:

也许您的“pindex.json”JSON 文件格式错误,json_encode 函数返回 null。

由于你没有告诉我json是怎样的,所以我做了这个例子。 调用 users.json

{
  "users" : [
    {"nome" : "GeekSilva", "pw" : "123"}
  ]
}

PHP 代码如下所示。

$nome = $_GET['nome'];
$pw = $_GET['pw'];

$data = ['nome' => $nome, 'pw' => $pw];

$inp = file_get_contents('users.json');

//Passing the second parameter to true will be returned as an array
$tempArray = json_decode($inp, true);

// push to $tempArray
$tempArray['users'][] = $data;


$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);

使用 json_decode 函数的第二个参数,我们得到一个数组,然后我们可以从那里添加一个带有通过 AJAX 传递的参数的元素。

【讨论】:

    【解决方案2】:

    第一个php没有console.log();可能要试试print_r()或者var_dump()

    下一步

    $tempArray = json_decode($inp);
    

    由于某种原因,这将返回一个 stdObject。要获取数组,您需要这样做

    $tempArray = json_decode($inp,TRUE);
    

    你只需要做一个数组:

    $tempArray[] = $data;
    

    【讨论】:

      猜你喜欢
      • 2016-03-08
      • 2017-11-30
      • 2017-11-10
      • 2014-03-13
      • 2013-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-05-22
      • 1970-01-01
      相关资源
      最近更新 更多