我想提交此表而无需刷新页面,但是当我提出需要我来操作页面。 什么是错我的代码? 这是我的表格:
<form class="ajax" action="/../addchannel/createUser.php" method="post" >
<input type="text" name="userName" placeholder="userName"><br>
<input type="text" name="email" placeholder="email"><br>
<input type="submit" value="submit" >
</form>';
这是我的脚本:
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find(['name']).each(function (index, value)) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
consol.log(response)
}
});
});
通过事件作为参数,并使用event.preventDefault()
例
$('form.ajax').on('submit', function (e) {
e.preventDefault();
ü忘记return false
在年底或防止违约。
$('form.ajax').on('submit', function (event) {
event.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
....
//or return false;
});
使用e.preventDefault()或return false;
防止表单提交
$('form.ajax').on('submit', function (e) {//Pass the event argument here
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find(['name']).each(function (index, value)) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
consol.log(response)
}
});
e.preventDefault();
//OR
return false;
});
使用event.preventDefault()
$('form.ajax').on('submit', function (e) {
e.preventDefault();
//code here
});
使用jQuery AJAX是不会阻止浏览器跟随窗体动作页。 要做到这一点,你应该避免浏览器通过简单的函数来做到这一点: e.preventDefault()
这里是你的代码:
//Pass the event argument (e)
$('form.ajax').on('submit', function (e) {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find(['name']).each(function (index, value)) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function (response) {
consol.log(response)
}
});
//Prevent Browser to follow form action link:
e.preventDefault();
//you can use also
// return false;
});
尝试这个..
<form method='post' action="javascript:mail();" >
<input type="text" class="input-large" id="user_name" name="name">
<input type="text" class="input-large" id="email" name="name">
<button type="submit" class="btn btn-primary">Submit</a>
</form>
function mail()
{
var name = $("#user_name").val();
var email = $("#email").val();
$.ajax({
type: "POST",
url: "contact.php",
data: "name=" + name+"&customer_mail="+email,
success: function(html) {
//do ur function
}
});
}