ajax提交表单为什么它不能回显$ _POST [英] ajax submit form why it cannot echo $_POST

查看:80
本文介绍了ajax提交表单为什么它不能回显$ _POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ajax提交表单进行测试(向自己的页面"new1.php"提交)

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.

这是new1.php页面

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>

推荐答案

在您的情况下,最好的选择是在PHP代码中使用json_encode以JSON格式检索值,然后通过数据对象访问这些值.

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.

示例:

PHP代码:

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代码:

$("#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.
});

这篇关于ajax提交表单为什么它不能回显$ _POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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