繁体   English   中英

如何在ajax请求页面中调用return false?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM