我目前收到200绿色响应,但是我的数据仍未写入json文件(即仍然为空)
JavaScript:
$(function() {
$('form#saveTemp').submit(function() {
let savdAta = JSON.stringify($('form#saveTemp').serializeObject());
//let tempName = savdAta.styleName;
console.log(savdAta);
//console.log(JSON.stringify($('form#saveTemp').serializeObject()));
$.ajax({
url: './php/data.php',
type: 'POST',
contentType: "application/json",
data: {
template: savdAta
},
success: function(msg) {
console.log('data sent to php file, but..');
}
});
return false;
});
});
savdAta
中控制台中的数据格式如下:即
{"styleName":"","fillType":"none","fillTrans":"0"}
PHP:
<?php
header('Content-Type: application/json');
if (!isset($_POST['savdAta']) && !empty($_POST['savdAta'])) {
$savdAta = $_POST['savdAta'];
$jsonObject = json_encode($savdAta);
file_put_contents('./data.json', $jsonObject);
}
更新:现在我得到以下内容,没有错误,但我的.json文件仍然是空白:
<?php
if (!empty($_POST['template'])) {
$savdAta = $_POST['template'];
file_put_contents('./data.json', $savdAta);
}
您的POST变量为template
,并且仅在未设置且不为空的情况下才执行,这不是您想要的,并且永远不会求值为true
:
//Not needed
//header('Content-Type: application/json');
if (!empty($_POST['template'])) {
$savdAta = $_POST['template'];
//This is already JSON
//$jsonObject = json_encode($savdAta);
file_put_contents('./data.json', $savdAta);
}