我有一个类似于这样的表单
<form action="receiver.pl" method="post">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
当单击“提交”时,我希望留在同一页,但仍然执行receiver.pl
,应该如何完成?
我有一个类似于这样的表单
<form action="receiver.pl" method="post">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
当单击“提交”时,我希望留在同一页,但仍然执行receiver.pl
,应该如何完成?
99%的情况下,我会使用XMLHttpRequest或fetch来处理这样的内容。然而,有一个不需要JavaScript的替代方案...
您可以在页面上包含一个隐藏的iframe,并将表单的目标属性设置为指向该iframe。
<style>
.hide { position:absolute; top:-1px; left:-1px; width:1px; height:1px; }
</style>
<iframe name="hiddenFrame" class="hide"></iframe>
<form action="receiver.pl" method="post" target="hiddenFrame">
<input name="signed" type="checkbox">
<input value="Save" type="submit">
</form>
我很少会选择这种方式。通常使用JavaScript更好,因为JavaScript可以......
最简单的答案:jQuery。做类似于这样的事情:
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
});
如果你想动态添加内容并且希望它能在多个表单中起作用,你可以这样做:
$('form').live('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
},'json');
return false;
});
data
参数将其显式发送到$.ajax
函数中,new FormData($(this)[0]);
并将enctype="multipart/form-data"
添加到表单中。请参见此答案:https://dev59.com/O2gv5IYBdhLWcg3wCcWZ#10899796 - Herman Schaaf使用HTTP / CGI的方法是让您的程序返回204(无内容)的HTTP状态代码。
var xhr = new XMLHttpRequest();
xhr.open("POST", '/server', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() { // Call a function when the state changes.
if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
// Request finished. Do processing here.
}
}
xhr.send("foo=bar&lorem=ipsum");
// xhr.send(new Int8Array());
// xhr.send(document);
receiver.pl
是在新窗口/选项卡中打开的吗? - Sandra Schlichting