【问题标题】:Why page is shown after POST request?为什么在 POST 请求后显示页面?
【发布时间】:2011-07-04 18:15:21
【问题描述】:

标签: javascript jquery post


【解决方案1】:

在提交处理程序的末尾执行return false;。否则,您不会阻止正常提交(发布到 test.php)发生

$("form#f").submit(function(){
            var result = "";
            $.ajax({
                async: false,
                type: "POST",
                url: "test.php",
                dataType: "script",
                success: function(data){
                    result = data;
                    alert(result);  // And move that here
                }
            });
            return false;  // Here

        });

【讨论】:

  • 老兄!你从我的评论中偷走了你的答案!开个玩笑:-P +1
  • @Endophage。哈哈...我认为您误解了 SO 的工作原理:)
  • @Jairo。什么“不起作用”?它还在发布表单,还是在您的 JS 控制台中出现错误?
【解决方案2】:

返回 false 的替代方法是使用 jQuery 的 event.preventDefault():

    $("form#f").submit(function(e){
        e.preventDefault();
        // do stuff
    });

【讨论】:

  • 我认为这不起作用的原因是它没有将alert 移动到成功回调中。 event.preventDefault 是比 return false 更好的解决方案,因为如果事件处理程序中存在未捕获的错误,它仍然会取消事件。
【解决方案3】:

@Jairo 我尝试了您的原始代码,它使用 CDN 工作。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-01
    • 2018-12-31
    • 2019-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多