0

我有 4 个输入,由 Ajax 4 数据发送到一个 php 文件:如何加载 json 文件,然后在 php 中添加新数据?

<input type="text" id="name">
<input type="text" id="surname">
<input type="text" id="mobile">
<input type="text" id="email">
<script>
var name = $("#name").val();
var surname = $("#surname").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
$.ajax({type:"POST",
url:"fill.php",
data:"name="+nombre+"&surname="+surname+"&mobile="+mobile+"&email="+email,
success:function(data) {

} }); JSON 文件:(people.json)

{
"1":
{
    "Name" : "Jhon",
    "Surname" : "Kenneth",
    "mobile" : 329129293,
    "email" : "jhon@gmail.com"
},
"2":
{
    "Name" : "Thor",
    "Surname" : "zvalk",
    "mobile" : 349229293,
    "email" : "thor@gmail.com"
}
}

这里我有一个错误的 fill.php 文件:

<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file));
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>

当我执行它时,它会删除所有 people.json 日期,并且每次我添加新数据时,它都会给我下一个结果:[{},{},{},{}]

4

2 回答 2

1

您需要向 json_decode 添加一个 secnod 参数,使其成为一个数组,试试这个

<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file),1);
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>
于 2013-01-27T00:50:54.150 回答
0

json decode 接受第二个参数,设置它,你会得到数组而不是 stdClass 对象。

于 2013-01-27T00:49:34.840 回答