繁体   English   中英

提交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文件的路径是正确的,但没有显示任何内容? 甚至没有“ fail div”。 有人对我有解决方案吗?

提前致谢!

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

成功:函数(xhr){警报(xhr);}

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
    }
?>

jQuery的:

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">

基于您的PHP源代码。

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

暂无
暂无

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

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