我在一个html页面中有两个表单。我想用这两种形式的结果更新一个单曲。(form1或form2显示相同的结果。DIV将使用来自.php文件的1行进行更新。
这是我的代码:
我的html页面(2个表单):
<form name="form1" id="form1" action="result.php" method="post">
<input type="text" name="data1">
<input type="text" name="data2">
<input type="submit" value="OK">
</form>
<form name="form2" id="form2" action="result2.php" method="post">
<input type="text" name="data3">
<input type="text" name="data4">
<input type="submit" value="OK">
</form>
<div id="resultDIV"></div>
使用的脚本:
$('#form1').submit(function () {
$.post('result.php', $('#form1').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
return false;
});
$('#form2').submit(function () {
$.post('result2.php', $('#form2').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
return false;
});
但它不起作用。这段代码在一个新窗口中打开result.php或result2.php。(已编辑)
使用event.preventDefault();
$('#form1').submit(function (e) {
e.preventDefault();
$.post('result.php', $('#form1').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
return false;
});
$('#form2').submit(function (e) {
e.preventDefault();
$.post('result2.php', $('#form2').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
return false;
});
几件事:
- 您是根据表单的id引用表单,但它们没有id。您必须将其
id
属性设置为form1
和form2
- 您没有用
</form>
关闭<form>
标记 - 您可以使用
.preventDefault()
阻止页面重定向
HTML:
<form id="form1" name="form1" action="result.php" method="post">
<input type="text" name="data1">
<input type="text" name="data2">
<input type="submit" value="OK">
</form>
<form id="form2" name="form2" action="result.php" method="post">
<input type="text" name="data3">
<input type="text" name="data4">
<input type="submit" value="OK">
</form>
<div id="resultDIV"></div>
JS:
$('#form1').submit(function (e) {
e.preventDefault();
$.post('result.php', $('#form1').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
});
$('#form2').submit(function (e) {
e.preventDefault();
$.post('result2.php', $('#form2').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
});
这是我现在的代码。。。总是result.php,它在一个新窗口中打开,而不是更新我的DIV
头和/头之间的脚本
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$('#form1').submit(function (e) {
e.preventDefault();
$.post('result.php', $('#form1').serialize(), function (data, textStatus) {
$('#resultDIV').append(data);
});
return false;
});
</script>
还有我的HTML文件(something.HTML):
<form name="form1" action="result.php" method="post" id="form1">
<input type="text" name="data1">
<input type="text" name="data2">
<input type="submit" value="OK">
</form>
<div id="resultDIV"></div>
好的,我用这个代码解决了(如果它能帮助其他人的话)
<script>
$(document).ready (function() {
$("form").submit(function () {
$.post("result.php",$(this).serialize(),function(texte){
$("div#resultDIV").append(texte);
});
return false;
});
});
</script>