【发布时间】:2016-10-13 16:49:54
【问题描述】:
我是 JS 的初学者,之前从未接触过 PHP。在搜索了几个小时之后,我拼凑了这件作品。我想要做的是有一个简单的表单,其中包含几个字段,这些字段被保存到 JSON 文件中。我希望每个后续条目都附加到文件的末尾,以便每个 JSON 对象都是人名和他们的评论。
使用下面的代码,我已经成功地将 something 传递给 PHP 脚本,并将条目附加到 json 文件中。但是 json 文件中显示的是这个(在两个条目之后):
[{"data":"$data"},{"data":"$data"}]
这是我的 HTML
<form method="POST">
<!-- NAME -->
<div id="name-group" class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" placeholder="">
<!-- errors will go here -->
</div>
<!-- EMAIL -->
<div id="comment-group" class="form-group">
<label for="comment">Comment</label>
<input type="text" class="form-control" name="comment" placeholder="">
<!-- errors will go here -->
</div>
<button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button>
</form>
我的 jquery
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'name' : $('input[name=name]').val(),
'comment' : $('input[name=comment]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'data/save.php', // the url where we want to POST
data : formData, // our data object
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(formData);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
还有我的 PHP
<?php
if( !empty( $_POST ) ){
$data = json_encode( $_POST );
if( json_last_error() != JSON_ERROR_NONE ){
exit;
}
$file = file_get_contents('comments.json');
$data = json_decode($file);
unset($file);
$data[] = array('data'=>'$data');
file_put_contents('comments.json',json_encode($data));
unset($data);
}
?>
谢谢
【问题讨论】:
-
我知道(很确定)它与 $data[] = array('data'=>'$data');行,但我不确定如何处理
-
变量在双引号内展开,而不是单引号。就像
bash和perl。 -
您根本不需要在
$data周围加上引号。使用array('data' => $data)
标签: php jquery json ajax forms