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

标签 javascript php jquery html ajax

我正在使用 ajax 提交表单进行测试(提交给自己页面“new1.php”)

我想要的是,点击提交按钮后,它会回显名字和姓氏。但是我不知道为什么提交后看不到名字和姓氏。

这里是new1.php页面

<?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 格式检索值,然后通过数据对象访问这些值。

例子:

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.
});

关于javascript - ajax提交表单为什么不能回显$_POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41589805/

相关文章:

javascript - 如何使用 React 防止点击时在 &lt;input type=submit> 中发布表单

javascript - 如何使用 getJSON 将 javascript 变量传递给 php

php - 防止 $_POST 轰炸

Javascript替换img文件

javascript - 获取背景图像尺寸

javascript - 使用 Javascript 在 forEach 中进行切换是不好的做法吗?

javascript - Node JS : How do I request multiple source codes from different websites?

javascript - 格式化日期选择器以发布到 MySQL 数据库

javascript - 使用 substr 在 Div 中插入 HTML

javascript - 在图像顶部动态添加元素