gpt4 book ai didi

javascript - 将用户添加到 Json 列表 #PHP #JS

转载 作者:太空宇宙 更新时间:2023-11-04 15:28:52 24 4
gpt4 key购买 nike

我们正在尝试从前端表单向 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);
?>

最佳答案

也许您的“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 传递的参数添加一个元素。

关于javascript - 将用户添加到 Json 列表 #PHP #JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44973290/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com