jquery,通过停留在同一页面上发送表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15358298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:53:34 来源:igfitidea点击:
jquery, send a form by staying on the same page
提问by Gradislava Bikkulova
I want to send a form without leaving my current page, so I'm using:
我想在不离开当前页面的情况下发送表单,所以我使用:
$('.myForm').on('submit', function(){
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
alert('ok');
}
});
return false;
});
but it doesn't work... any idea please?
但它不起作用......有什么想法吗?
回答by Siva Charan
Do this way:-
这样做:-
$(document).on('submit', '.myForm', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
alert('ok');
}
});
e.preventDefault();
});
回答by Roger
Here is an example
这是一个例子
<form name="frm" method="POST" action="">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
The jquery part
jquery部分
$("#update").click(function(e) {
e.preventDefault();
var name = $("#name").val();
var last_name = $("#last_name").val();
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'insert.php',
success:function(data) {
alert(data);
}
});
});
The insert.php
page
该insert.php
页面
<?php
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into TABLE_NAME values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
?>
Hope this helps
希望这可以帮助
回答by Pragnesh Chauhan
use event.preventDefault();
用 event.preventDefault();
$('.myForm').on('submit', function(event){
event.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
alert('ok');
}
});
//return false;
});