我有一个表单,我正试图用ajax和常规提交一起提交,常规提交用于创建pdf,ajax提交用于显示预览的html示例,如果我单独使用它们,或者在预览提交之前使用create pdf,这两个示例都很好,但如果在预览提交之后使用sumbit for pdf,它就不起作用了,没有任何事情会像禁用常规提交按钮那样发生。我的代码如下所示,请注意,如果我先使用ajax提交,两者都可以正常工作,只是常规帖子不起作用。
<script type="text/javascript">
$('#submitpdf').submit(function() {
return true;
});
$('#submitpreview').click(function() {
$('#form').submit(function(event) { // 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: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false;
});
});
</script>
这是表单标签和提交按钮的HTM1:
<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data">
<input type="submit" id="submitpdf" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
<input id="submitpreview" type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
</form>
另一件需要注意的事情是,使用ajax时,我想提交到"test.php",使用常规提交时,我希望提交到"dopdf.php"。
submitPreview按钮点击的代码在我看来不正确(在点击处理程序上,你基本上是在注册提交事件代码!)。请尝试更改为此干净版本。此外,请确保将事件处理程序代码封装在document.ready
事件中,以避免其他问题。
此外,您还需要读取表单的method
属性,而不是GET
属性。
$(function(){
$('#submitpreview').click(function(e) {
e.preventDefault(); // prevent the default form submit behaviour
var _this=$(this).closest("form");
$.ajax({ // create an AJAX call...
data:_this.serialize(), // get the form data
type: _this.attr('method'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
});
由于表单操作值设置为dopdf.php
,因此当用户单击该按钮时,它将提交给dopdf.php
。您不需要任何额外的jQuery点击处理程序。
您可以执行以下
-
你的脚本像这个
$('#form').submit(function() { $.ajax({ // create an AJAX call... data: $(this).serialize(), // get the form data type: $(this).attr('GET'), // GET or POST url: 'test.php', // the file to call success: function(response) { // on success.. $('#created').html(response); // update the DIV } }); });
和形式。不要更改它