I have a basic form that includes an input
and a submit button
. I'd like the value of the input
to be converted into JSON
and then that JSON
to be placed in a file on the server for use later. I'm using AJAX and a small PHP
script to handle the data and the file creation, however the JSON
file (test.json
) is never created.
HTML Markup
<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"
}
]
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…