如何通过一次单击将表单发布到两个不同的页面? [英] How to post form to two different pages with a single button click?
问题描述
我有一个带有单个按钮的表单,如下所示:
I have a form with a single button like below:
<form name="sampleForm" id="sampleForm" method="post" action="" enctype="multipart/form-data">
<input type="text" id="biosample" name="biosample" class="sample"/>
<input type="text" id="library" name="library" class="sample"/>
<input type="submit" name="btnAdd" id="btnAdd" class="buttonsub" value="NEXT>>">
</form>
Ajax代码是:
<script>
$(document).ready(function(){
var encoded_project_id = $('#encoded_project_id').val();
$('#sampleForm').on('submit', function(){
var target = 'windowFormTarget';
window.open('', target, 'width=500,height=300');
this.setAttribute('target', target);
$.post('postdata.php', $(this).serialize(), function(){
window.location.href = 'phases.php?edit='+encoded_project_id;
}).fail(function(){
window.location.href = 'sample.php?edit='+encoded_project_id;
});
});
});
</script>
现在,当单击按钮时,我想将上述表格中的数据分2页发布-handler.php和postdata.php
Now when button is clicked, I want to post the data from the above form in 2 pages - handler.php and postdata.php
Handler.php应该在新的javascript窗口中打开,而postdata.php应该在相同的标签和窗口中打开.
Handler.php should open in a new javascript window and postdata.php should open in same tab and same window.
如何实现?
推荐答案
看来您正在使用jQuery,因此请更改此内容:
It would seem you are using jQuery, so change this:
$(document).ready(function () {
document.getElementById('sampleForm').onsubmit = function (e) {
var req = new XMLHttpRequest();
req.open('POST', 'test.php', true);
req.send();
}
});
对此:
$(document).ready(function(){
$('#sampleForm').on('submit', function(){
$.post('postdata.php', $(this).serialize(), function(){
console.log('success');
}).fail(function(){
console.log('error');
});
});
});
您应该做两件事.首先添加
You should do two things. First add
<form target="_blank" action="handler.php"></form>
这将确保单击提交"按钮时,表单将打开一个新窗口.
This will ensure when the submit button is clicked that the form will open a new window.
然后您需要像这样拦截提交:
Then you need to intercept the submit like so:
document.getElementById('sampleForm').onsubmit = function(e){
//xmlHTTPRequest function
//This is where you send your form to postdata.php
}
上面的代码将首先被调用,您可以使用异步发送表单XMLHTTPRequest 指向postdata.php
的对象.该函数结束后,form
的默认行为将开始,您的handler.php
将收到该表格.
The code above will be called first and you can send your form with the asynchronous XMLHTTPRequest object to postdata.php
. After that function ends, the default behavior of the form
will start and your handler.php
will receive the form.
这篇关于如何通过一次单击将表单发布到两个不同的页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!