【问题标题】:Ajax > PHP > append json with form dataAjax > PHP > 用表单数据附加 json
【发布时间】: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');行,但我不确定如何处理
  • 变量在双引号内展开,而不是单引号。就像bashperl
  • 您根本不需要在$data 周围加上引号。使用array('data' =&gt; $data)

标签: php jquery json ajax forms


【解决方案1】:

您引用了$data,这会阻止变量被扩展。您也没有将用户输入参数放入数组中,而是尝试使用 $data 将数组放入自身中。

$data[] = array('name' => $_POST['name'], 'comment' => $_POST['comment']);

如果要将变量插入字符串,则必须使用双引号,而不是单引号。见What is the difference between single-quoted and double-quoted strings in PHP?

我看不出调用json_encode($_POST) 的代码的意义所在。这不会对发布数据执行任何有用的验证,因为可以对任何可以发布的内容进行编码。

也不需要在 Javascript 中使用FormData。这通常仅在您上传文件时才需要。对于其他输入,您可以使用.serialize() 方法:

    var formData = $(this).serialize();

【讨论】:

  • 好的,所以我已经尝试过了,现在我在我的 json 文件中得到:[{"data":null}]。
  • 为什么要将$data 放入数组中?那是保存您从文件中读取的数组的变量。您不应该将用户输入放入数组中吗?
  • 输入在$_POST['name']$_POST['comment']
  • 谢谢,最后一部分帮助很大。我现在已经通过将行更改为 $data[] = array('name'=&gt;$_POST['name'],'comment'=&gt;$_POST['comment']); 来正确地将信息写入 json 文件
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-10
  • 2016-04-27
  • 2016-12-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多