我有一个基本形式,包括一个 input 和一个提交 button。我希望将 input的值转换为 JSON,然后将该 JSON 放置在服务器上的文件中以供后来使用。 我正在使用AJAX和一个小的 PHP 脚本来处理数据和文件创建,但是 JSON 未创建。
HTML标记:
<input id="title" type="text" name="title" value="Page Title"/>
<button type="submit" value="submit" id="submit">Submit</button>
JS:
var submit = $('#submit');
var title = $('#title');
function createJSON() {
var jsonObj = [];
title.each(function() {
var value = $(this).val();
var item = {};
item.title = value;
jsonObj.push(item);
});
$.ajax({
url: "create-file.php",
data: {
data: jsonObj
},
type: "POST"
});
}
submit.on('click', function() {
createJSON();
});
PHP (create-file.php):
<?php
$json = $_POST['data'];
$info = json_encode($json);
$file = fopen('test.json','w+') or die("File not found");
fwrite($file, $info);
fclose($file);
?>
JSON:
[
{
title: "Page Title"
}
]