[英]AJAX Post to .PHP to JSON Data-set || PHP File
Afternoon guys/gals, 下午伙计们
I'm relatively new to using AJAX to POST information to a JSON file and I am not sure what the .php file should look like to process it. 我相对较不熟悉使用AJAX将信息发布到JSON文件中的情况,但不确定.php文件应如何处理。 I have very little experience with .php.
我对.php的经验很少。 Am I on the right track?
我在正确的轨道上吗? I've looked a lot of examples but most of them only have pieces of the .php file to process it.
我看了很多示例,但其中大多数都只有一部分.php文件来处理。 I am trying to inject the "task" into the JSON file which I then use handlebars to read on another page.
我试图将“任务”注入JSON文件,然后使用把手在另一页上阅读。
function fnCreateTask() {
var url = "save.php";
var title = $("#TaskTitle").val();
var date = $("#TaskDate").val();
var desc = $("#TaskDescription").val();
var info = {
Title: title,
Date: date,
Description: desc
};
var body = JSON.stringify(info);
$.ajax({
type: "POST",
url: url,
contentType: 'application/json',
data: body,
dataType: 'json',
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
}
<?php
$fp = fopen('careers.json', 'w');
fwrite($fp, $_POST = json_decode(file_get_contents('php://input'), true););
fclose($fp);
?>
To create a JSON in PHP : 要在PHP中创建JSON:
<?php
$array = array(
"name" => "toto",
"lastname" => "lafraise",
"age" => 33
);
$fp = fopen('careers.json', 'w');
fwrite($fp, json_encode($array));
fclose($fp);
$.ajax POST (or GET for that matter) data will be x-form encoded by default when sent to the server. 将$ .ajax POST(或GET)数据发送到服务器时,默认情况下将采用x格式编码。 You can do
你可以做
on the client 在客户端上
//object for the data
var data = {
title: $("#TaskTitle").val(),
date: $("#TaskDate").val()
};
$.ajax({
type: "POST",
url: "save.php",
data: data,
error: function (err) {console.log(err)},
success: function (data) {
alert('Task Created.');
location.reload();
}
});
and on the server 并在服务器上
// as a separate object to be safe
$dataobj['title'] = $_POST['title'];
$dataobj['date'] = $_POST['date'];
// write json_encode object to file
file_put_contents ( 'filename.json' , json_encode($dataobj));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.