【问题标题】:Unable to get value from serialize data无法从序列化数据中获取价值
【发布时间】:2018-04-03 16:27:59
【问题描述】:

实际上我只是试图从序列化中获取所有输入数据,但我得到 int 类型的值,如年龄和 id,但无法获取名称的值。 以下是我的代码。

    <html>
    <body>
        <form id ="form" method="post" class= "form">
            Name<input type = "text" name = "name" /><br>
            Age<input type = "number" name = "age" /><br>
            ID<input type = "number" name = "id" /><br>
            <input type = "submit" name = "submit"><br/>
        </form>
        <p id="result"></p>
        <script
            src="https://code.jquery.com/jquery-3.2.1.min.js"
            integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>
        <script>
            $(document).ready(function () {
                $("#form").submit(function () {
                    var data = $("#form").serialize();
                    insertStudent(data);
                    return false;
                });
                function insertStudent(data) {
                    $.ajax({
                        url: 'process.php',
                        data: data,
                        type: 'POST',
                        dataType: 'json',
                        success: function (data, textStatus) {
                            $("#result").html(data);
                        },
                        error: function () {
                            alert('Not OKay');
                        }
                    });
                }
            });
        </script>
    </body>
</html>

进程.php

print_r($_POST);// give error but if i try to get id then
print_r($_POST["id"])// print value
print_r($_POST["name"])// doesn't print name

【问题讨论】:

  • 您可以发布您的 xhr 请求正文和标头吗?
  • 您的代码单独运行良好:jsfiddle.net/85rkbx27。您需要在浏览器控制台中调试请求。检查请求的内容以确保它符合您的预期。
  • 您没有名称为 id 的表单元素,因此您在错误的页面上
  • 在成功函数中你正在做$("#result").html(data);,但ajax调用有dataType: 'json'。改为dataType: 'html'

标签: php jquery ajax forms serialization


【解决方案1】:
$(document).ready(function () {
    $("#form").submit(function (e) {
        //e.preventDefault();
        var data =$(this).serialize();
        insertStudent(data);
        return false;
    });
    function insertStudent(data) {
        $.ajax({
            url: 'process.php',
            data: data,
            type: 'post',
            dataType: 'html',
            success: function (data, textStatus) {
                $("#result").html(data);
                // console.log(data);
            },
            error: function () {
                alert('Not OKay');
            }
    });
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-04
    • 2018-11-30
    • 2017-02-13
    • 2021-10-09
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2021-09-17
    相关资源
    最近更新 更多