【发布时间】: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