我想在按下表单中的提交按钮时进行AJAX调用。
InFact我不能删除<form>
,因为我也想进行客户端验证。
我试过这段代码。
<form name="search" >
Name: <input type="text" name="name1"/>
Age: <input type="text" name="age1"/>
<input type="submit" name="Submit" value="Submit" onclick="makeSearch()"/>
</form>
JS
function makeSearch(){
alert("Code to make AJAX Call");
}
使用此代码后,alert()未显示但页面已重新加载。 我想阻止页面重新加载并调用JS函数。
谢谢
答案 0 :(得分:30)
将onsubmit
属性添加到form
代码:
<form name="search" onsubmit="return makeSearch()" >
Name: <input type="text" name="name1"/>
Age: <input type="text" name="age1"/>
<input type="submit" name="Submit" value="Submit"/>
</form>
javascript在最后添加return false
:
function makeSearch() {
alert("Code to make AJAX Call");
return false;
}
答案 1 :(得分:27)
正确的jQuery方式是:
$("form").on('submit', function (e) {
//ajax call here
//stop form submission
e.preventDefault();
});
就像你说的那样,你也可以删除<form>
元素,然后将ajax调用绑定到按钮的click
事件。
答案 2 :(得分:1)
使用 jQuery.post,然后更改提交按钮。
创建提交按钮是为了通过POST (native method, not ajax)向服务器发送数据,我建议仅在特殊情况下使用它,例如上传文件时。
如果继续使用提交按钮获取ajax请求,那么IE会遇到很多问题。
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script language="javascript">
function makeSearch()
{
if(validateIdata())
{
alert("send ajax request");
return;
$.ajax({
type: 'POST',
url: url, //- action form
data: {name1:$('#name1').val(),age1:$('#age1').val()},
success: function(){
alert('success');
}
});
}
}
function validateIdata()
{
if($('#name1').val() =='')
{
alert("Invalid Name");
return false;
}
if($('#age1').val() =='')
{
alert("Invalid Age");
return false;
}
return true;
}
</script>
</head>
<body>
<form name="search" >
Name: <input type="text" id="name1" name="name1"/>
Age: <input type="text" id="age1" name="age1"/>
<input type="button" name="Submit" value="Submit" onclick="makeSearch()"/>
</form>
</body>
</html>
答案 3 :(得分:0)
<form name="search" >
Name: <input type="text" name="name1"/>
Age: <input type="text" name="age1"/>
<input type="submit" name="Submit" value="Submit" onclick="return makeSearch();"/>
</form>
function makeSearch(){
alert("Code to make AJAX Call");
}
只需在onclick函数中使用return它就会对你有好处
答案 4 :(得分:0)
document.getElementById("bt1").type='submit';
document.getElementById("bt1").onclick="";
var elem = document.getElementById("bt1");
if (typeof elem.onclick == "function") {
elem.onclick.apply(elem);
}
<form id="org" action="">
<fieldset class="log">
<legend>Log in</legend>
<label for="uname">Username</label>
<input type="text" name="uname" id="uname" value="" required/><br />
<label for="pword">Password</label>
<input type="password" name="pword" id="pword" value="" required/><br />
<input type="button" onclick="organizer()" value="LOG IN" class="red-btn" id="bt1"/>
</fieldset>
</form>
答案 5 :(得分:-3)
最后我得到了答案
$("form").live("submit", function() {
makeSearch();
return false;
});