2017-07-07 14 views
1

我們試圖從前端表單向Json文件添加一些新用戶。將用戶添加到Json列表#PHP #JS

我們通過Js傳遞從表單中獲取的代碼,然後我們試圖通過PHP(通過PHP)將用戶插入的值傳遞給json文件。

從HTML摘自JS

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

提取文件

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); 
    ?> 
+1

問題是什麼/問題? –

+2

'$ .get(「utenti.php」,{nome:newNom.value,pw:newPass.value});'爲了您自己和其他人的安全請*不要*通過GET發送密碼 –

+0

是那些標籤? – apokryfos

回答

1

也許你的「pindex.json」JSON文件格式不正確,json_encode函數返回null。

由於您沒有告訴我json是如何,我做了這個例子。 Called 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傳遞的參數添加元素。

0

第一個PHP沒有console.log();可能想嘗試print_r()var_dump()

接下來的

$tempArray = json_decode($inp); 

這將返回一個stdObject出於某種原因。爲了得到你需要做的

$tempArray = json_decode($inp,TRUE); 

你應該只需要做一個數組的數組:

$tempArray[] = $data;