dppb79372 2017-01-11 11:33
浏览 318
已采纳

ajax提交表单为什么它不能回显$ _POST

I'm test using ajax submit form (submit to myself page "new1.php")

The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.

here is new1.php page

<?php 
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>"; 
 ?>  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

</head>
<body>
    <form id="myform" action="new1.php" method="post">
        Firstname : <input type="text" name="firstname"> <br>
        Lastname : <input type="text" name="lastname"> <br>
        <input type="submit" value="Submit">
    </form>

        <script>
        // this is the id of the form
$("#myform").submit(function(e) {

    $.ajax({
           type: "POST",
           url: 'new1.php',
           data: $("#myform").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert('yeah'); // show response from the php script.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});
    </script>
</body>
</html>
  • 写回答

5条回答 默认 最新

  • dongxing2015 2017-01-11 11:50
    关注

    In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.

    Example:

    PHP code:

    if($_POST)
    {
        $result['firstname'] = $_POST['firstname'];
        $result['lastname'] = $_POST['lastname'];
    
        echo json_encode($result);
        die(); // Use die here to stop processing the code further 
    }
    

    JS code:

    $("#myform").submit(function (e) {
    
        $.ajax({
            type : "POST",
            url : 'new1.php',
            dataType : 'json', // Notice json here
            data : $("#myform").serialize(), // serializes the form's elements.
            success : function (data) {
                alert('yeah'); // show response from the php script.
                // make changed here
                $('input[name="firstname"]').text(data.firstname);
                $('input[name="lastname"]').text(data.lastname);
            }
        });
    
        e.preventDefault(); // avoid to execute the actual submit of the form.
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64