繁体   English   中英

序列化表单并使用POST方法使用ajax发送序列化的数据

[英]serialize a form and send the serialized data with ajax using POST method

我正在尝试序列化表单,并使用POST方法使用ajax发送序列化的数据。

index.php

<form id ="form" class = "form">
        <input type = "text" name = "name" />           
        <input type = "number" name = "age" />
        <input type = "number" name = "id" />
        <input type = "submit" name = "submit"><br/>
</form>
<p id = "result"></p>

jQuery片段

<script>
    $(document).ready(function(){
        $("#form").submit(function(){
            var data = $("#form").serialize();
            insertStudent(data);
            return false ;
        });
        function insertStudent(data){
            $.post("process.php" , { data : data} , function(str){
            $("#result").html(str);
            });                 
        }
   });
</script>

process.php

$ret = $_POST["data"];
echo "<br />".$ret["name"];

现在,结果是:

注意:未定义的索引:第3行的C:\\ xampp \\ htdocs \\ try.php中的名称

当我尝试回显$ _POST [“ data”]时,结果是:

名称= Ahmed&age = 111&id = 222

我如何分别使用每个名称,例如:$ _POST [“ name”] ... $ _POST [“ age”] ... $ _POST [“ id”]?

问题在于您将数据发送到服务器的方式:

{data: data}

将您的序列化数据变成一个参数,而不是serialize()收集的一系列参数。 只需将其更改为:

data

编辑(添加显式示例):以下(和以上)有效。 如果它不适合您,则您的php代码中还有其他错误。

index.php:

    <?php
echo '<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $("#form").submit(function(){

            var data = $("#form").serialize();
            insertStudent(data);
            return false ;
        });
        function insertStudent(data){

            $.post("process.php" , data , function(str){
            $("#result").html(str);

            });                 
        }
   });
</script>
</head>
<body>
<p>test of form</p>
<form id ="form" class = "form">
        <input type = "text" name = "name" />           
        <input type = "number" name = "age" />
        <input type = "number" name = "id" />
        <input type = "submit" name = "submit"><br/>
</form>
<p id="result"></p>
</body>
</html>';
?>

process.php:

<?php
print_r($_POST);
echo "<br/>"; 
foreach($_POST as $key=>$value){
    echo $key.": '".$value."'<br/>";
}
?>

结果输出:

Array ( [name] => Whatevernameyoutype [age] => whateverageyoutype [id] => whateveridyoutype ) 
name: 'Whatevernameyoutype'
age: 'whateverageyoutype'
id: 'whateveridyoutype'

您可以使用$ _POST [“ KEYNAMEHERE”];来访问任何已发布的参数,而不是循环。

    function insertStudent(data){
        $.ajax({
            url: 'process.php',
            data: data,
            type: 'POST',
            dataType: 'json',
            success: function(str){
                 $("#result").html(str);
            }
        });     
    }

然后在您的PHP文件中打印$ _POST :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM