首页 > 解决方案 > 从表单数据中获取 JSON

问题描述

我正在编写一个代码来获取使用表单发送的 JSON 参数。

我有这个 html

<form action="jsonfile.php" method="POST" name="myForm" enctype="application/json">
    <p><label for="first_name">First Name:</label>
    <input type="text" name="first_name" id="fname"></p>

    <p><label for="last_name">Last Name:</label>
    <input type="text" name="last_name" id="lname"></p>

    <input value="Submit" type="submit" onclick="submitform()">
</form>

和这里的 json

<script>
    var formData = JSON.stringify($("#myForm").serializeArray());

    $.ajax({
    type: "POST",
    url: "jsonfile.php",
    data: formData,
    dataType: "json",
    contentType : "application/json",
    success: function(result){

    }
  });
</script>

现在,我想在另一个名为JSONFILE.PHP的文件中将上述表单的值作为 json 发送。我真的不知道应该用什么将数据装饰成 JSON DATA。

谢谢你。

标签: phphtmljson

解决方案


    // HTML Code
<form method="POST" name="myForm" id="myForm" enctype="application/json" onsubmit="return false">
    <p><label for="first_name">First Name:</label>
        <input type="text" name="first_name" id="fname"></p>
    <p><label for="last_name">Last Name:</label>
        <input type="text" name="last_name" id="lname"></p>

    <input value="Submit" type="submit" >
</form>

   // JavaScript Code
<script>
    $("#myForm").submit(function () {
        var formData = JSON.stringify($("#myForm").serializeArray());
        $.ajax({
            type: "POST",
            url: "jsonfile.php",
            data: formData,
            dataType: "json",
            contentType: "application/json",
            success: function (result) {

            }
        });
    });
</script>

// PHP Code jsonfile.php
    <?php
    $data = json_decode(file_get_contents('php://input'), true);
    if ($data) {
        print_r($data);
    }
    ?>

推荐阅读