我有 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 日期,并且每次我添加新数据时,它都会给我下一个结果:[{},{},{},{}]