我有4个输入并使用Ajax将数据发送到php文件: 现在我很好奇如何将这些数据附加到json文件?
<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:"wjson.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"
}
}
wjson.php文件:
<?php
$nane = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$str_datos = file_get_contents("people.json")
//add new data to people.json
?>
通过people.json文件在我的服务器中的方式
答案 0 :(得分:1)
// in your wjson.php file
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$data = array(
'Name'=>$name,'surname'=>$surname,
'mobile'=>$mobile,'email'=>$email
);
$prevData = file_get_contents("people.json");
$prevData = json_decode($prevData,true);
$jsonData = json_encode(array_merge($prevData,array($data)));
file_put_contents('people.json',$jsonData);
答案 1 :(得分:0)
你已经做了太多额外的工作
<?php
$str_datos = file_get_contents("people.json",true);
$str_datos[]=$_POST;
file_put_contents('people.json',json_encode($str_datos);
?>
答案 2 :(得分:0)
将数据附加到json文件中试试这个。
<?php
if(file_exists("people.json")){
$prevdata = file_get_contents("people.json");
$newdata = $prevdata.','.json_encode($_POST);
file_put_contents("people.json", $newdata);
}else{
$data = json_encode($_POST);
file_put_contents("people.json", $data);
}
?>
答案 3 :(得分:0)
试试这个
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<form>
<input type="text" id="name">
<input type="text" id="surname">
<input type="text" id="mobile">
<input type="text" id="email">
<input type="button" id="save" value="Save" />
</form>
<script>
$(document).ready(function(){
$('#save').click(function(){
var name = $("#name").val();
var surname = $("#surname").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
$.ajax({
type: "post",
url: "wjson.php",
data : {name : name, surname : surname, mobile: mobile, email : email },
success:function(data) {
console.log(data);
},
error:function(data){
console.log(data);
}
});
});
});
</script>
并用
替换wjson.php文件if(file_exists('people.json'))
{
$data = $_POST;
$people = file_get_contents("people.json");
$people = json_decode($people,true);
$json = json_encode(array_merge($people,array($data)));
file_put_contents('people.json',$json);
}
else
{
$json = json_encode($_POST);
file_put_contents('people.json',$json);
}