提交 php 表单而不刷新页面


Submit form for php without refreshing page

我已经搜索了许多解决方案,但没有成功。

我有一个 html 表单;

<form id="objectsForm" method="POST">
      <input type="submit" name="objectsButton" id="objectsButton">
</form>

这用于菜单按钮。

我正在使用 jquery 来防止网站刷新;

$('#objectsForm').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: '/php/objects.php',
        data: $('#objectsForm').serialize(),
        success: function () {
            alert('success');
        }
    });
});

在我的 php 文件中,我尝试将文本回显到我的网站正文;

<?php
if (isset($_POST["objectsButton"])){
     echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>

我知道我的 php 文件的路径是正确的,但它没有显示任何内容?甚至不是"失败的div"。有人为我提供解决方案吗?

提前感谢!

成功函数采用两个参数。第一个参数是从 php 文件返回的内容。尝试将其更改为:

success: function (xhr)

{ alert(xhr);}

基于您的 php 源代码。

$.ajax({
    type: 'post',
    dataType: "html", // Receive html content
    url: '/php/objects.php',
    data: $('#objectsForm').serialize(),
    success: function (result) {
        $('#divResult').html(result);
    }
});

PHP脚本在服务器上运行,这意味着你所做的任何回显都不会出现在用户端。

与其回显 html,不如回显 json 编码的成功/失败标志,例如 0 或 1。

您将能够在成功函数中获得该值,并使用jQuery在网页上放置div。

.PHP:

<?php
    if (isset($_POST["objectsButton"])){
         echo json_encode(1); // for success
    } else {
        echo json_encode(0); // for failure
    }
?>

j查询:

var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
    type: 'post',
    url: '/php/objects.php',
    dataType: 'json',
    data: formData,
    success: function (response) {
        if (response == 1) {
            alert('success');
        } else {
            alert('fail');
        }
    }
});

编辑:

要包含该按钮,请尝试使用以下方法(就在$.ajax块之前,请参阅上文):

formData.push({name:this.name, value:this.value });

此外,为您的按钮提供 value 属性:

<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">