【问题标题】:PHP JQUERY AJAX FORM Submit ResponsePHP JQUERY AJAX 表单提交响应
【发布时间】:2015-12-21 10:03:21
【问题描述】:

当我尝试使用 php 执行常规 GET 提交时,我使用 php 构建了一个非常详细的表单,它工作得很好,但我需要使用 ajax 执行此操作,因为我需要使用 php 中的一些信息进行实时预览文件,我熟悉 PHP、HTML、CSS,但我没有使用 ajax 的经验

所以我的表单是这样的,它有两个提交按钮,我担心预览按钮。基本上我希望页面提交到 php dopdf.php 并从中带回结果。

<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data">
<!-- Lots of input -->
<input type="submit" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
<input type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />

这是我用来通过 ajax 进行汇总的 jquery:

<script>
$('#form').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
    data: $(this).serialize(), // get the form data
    type: $(this).attr('GET'), // GET or POST
    url: $(this).attr('dopdf.php'), // the file to call
    success: function(response) { // on success..
    //    $('#created').append(response); // update the DIV
    alert(response);
    }
});
return false; // cancel original event to prevent form submitting
});
</script>

这是我正在尝试的测试代码,如果可行,我会将数据放入 if 语句中:

if (isset($_GET['preview'])) { ?>
   <?php echo = "This is a test";  exit();?>
<?php } else {
   // This is for the other submit button.
}

我遇到的问题是 ajax 工作,我在警报中得到响应,但我得到的警报响应与我发布的页面相同,因为我从 document.php 发布此表单,所以我正在获取文档.php 返回。

【问题讨论】:

  • 您可以使用按钮而不是提交按钮,并在单击该按钮时调用该函数而不是$('#form').submit(function() {
  • 能否请您包含您得到的错误,另外您可以使用console.log() 而不是alert() 以便在测试时更好地查看您的结果。

标签: javascript php jquery ajax forms


【解决方案1】:

设置网址时出错。以下应该是正确的:

$(this).attr('action')

【讨论】:

  • 嗨,这确实解决了在警报框中返回同一页面的问题,但是现在有些警报框显示没有值而不是我的回显语句。感谢您的帮助
【解决方案2】:

我认为你实际上做了两次。当您按下按钮时,它正在运行 javascript,但也会像往常一样处理提交。

您需要告诉浏览器不要像现在使用 js/Ajax 那样进行正常提交,所以将此行添加到您的 javascript 中

另外你在设置 ajax 参数时有一些错误。

使用

<script type="text/javascript">
$('#form').submit(function(event) { // catch the form's submit event
    event.preventDefault();

    $.ajax({ // create an AJAX call...

        data: $(this).serialize(), // get the form data
        type: $(this).attr('method'), // GET or POST
        url: $(this).attr('action'), // the file to call
        success: function(response) { // on success..
        //    $('#created').append(response); // update the DIV
        alert(response);
        }
    });

});
</script>

【讨论】: