[英]How to call return false in ajax requests page?
如何調用return false;
在ajax請求頁面?
首先,當我按下submit button
,它將調用return checkform(this);
並且在function checkform ( form )
中將使用ajax發布頁面test.php
在test.php
中,我可以使用return fales;
中斷表單id="f1"
我測試了但沒用,我該怎么做?
的index.php
<form method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" id="f1">
<label>
Your Username
</label>
<input type="text" name="username" id="username">
<br>
<label>
Your Password
</label>
<input type="password" name="password" id="password">
<br>
<input name="submit" type="submit" value="Sign in"/>
<span id="mySpan_username_password"></span>
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
$.ajax
(
{
url: 'test.php',
type: 'POST',
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
}
}
)
}
</script>
<form id="f2">
<input type="text" name="username_send_value" value="xx"/>
<input type="text" name="password_send_value" value="yy"/>
</form>
test.php的
<script>
return faalse;
</script>
您可以對ajax請求返回error
響應,例如404
。
test.php的
<?php
header('HTTP/1.0 404 Not Found');
?>
發生這種情況是因為您的checkform
方法會發出ajax調用,然后繼續前進。 它不等待ajax響應,這是因為ajax調用具有默認的異步行為。
為了對其進行修復,首先需要確定是否要使ajax調用異步。
如果async:false
function checkform ( form )
{
var response=false;
$.ajax({
url: 'test.php',
type: 'POST',
async:false,//just add async:false here
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
response=true;
}
});
return response;
}
如果async:true
將回調傳遞為參數,並在回調中處理代碼。
function checkform ( form ,callback)
{
var response=false;
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
callback(true);
}
error: function(data){
callback(false);
}
});
}
方法調用:
checkform(form,function(response){
if(response===true)
//....
else
//...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.