阿贾克斯> PHP>将JSON附加到表单数据 [英] Ajax > PHP > append json with form data

查看:114
本文介绍了阿贾克斯> PHP>将JSON附加到表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JS的初学者,以前从未接触过PHP.经过数小时的搜查,我把这部分拼凑了一下.我正在尝试做的是,有一个简单的表单,其中包含几个保存到JSON文件中的字段.我希望将每个后续条目追加到文件末尾,以便每个JSON对象都是该人的姓名及其注释.

I'm pretty beginner with JS, and I've never touched PHP before. After scouring SO for hours and hours, I've cobble together this piece. What I'm trying to do, is have a simple form with a couple of fields which get saved into a JSON file. I would like each subsequent entry to append to the end of the file, so that each JSON object is the person's name, and their comment.

使用以下代码,我已经能够成功地将 something 传递给PHP脚本,并将条目追加到json文件中.但是,在json文件中显示的内容是这样的(在两次输入之后):

With the below code, I've successfully been able to pass something to the PHP script, and append entries into the json file. But what shows up in the json file is this (after two entries):

[{"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,它阻止了变量的扩展.您也没有将用户输入参数放入数组,而是尝试使用$data将数组放入自身.

You're quoting $data, which prevents the variable from being expanded. You're also not putting the user input parameters into the array, you're trying to put the array into itself by using $data.

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

如果要将变量插值到字符串中,则必须使用双引号而不是单引号.参见之间的区别是什么在PHP中使用单引号和双引号的字符串?

If you want to interpolate a variable into a string, you have to use double quotes, not single quotes. See What is the difference between single-quoted and double-quoted strings in PHP?

我看不到调用json_encode($_POST)的代码要点.这不会对发布数据执行任何有用的验证,因为可以对任何可以发布的内容进行编码.

I don't see the point of the code that calls json_encode($_POST). That doesn't perform any useful validation of the post data, since anything that can be posted can be encoded.

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

There's also no need to use FormData in the Javascript. That's generally only needed if you're uploading a file. For other inputs, you can use the .serialize() method:

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

这篇关于阿贾克斯&gt; PHP&gt;将JSON附加到表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆