【问题标题】:Why does $.ajax() cause the wep page to postback twice?为什么 $.ajax() 会导致 wep 页面回发两次?
【发布时间】:2014-07-24 17:44:33
【问题描述】:

谁能告诉我为什么这个 $.ajax() 会导致网页回发两次?不应该只开一次吗?

这是我在 Visual Studio 中调试时看到的,它导致服务器端脚本运行两次。我正在使用 JQuery 版本 2.0.0 。

ThrobblerAnimationBegin() 函数显示处理图标动画,让最终用户知道网页正忙于执行脚本。 @{} 括号是服务器端脚本,这就是我能够通过使用调试断点判断何时对服务器端后端进行回发的方式。

谢谢...

@{
    string foo = "Me Me Me";
    foo += ", fee fee fee";
}<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <title>BookItOut - A New Dawn In Auto Pricing"</title>
        <script type="text/javascript" src="~/Member/Scripts/jquery-v2.0.3/jquery-v2.0.3.min.js"></script>
        <script type="text/javascript">
            function ThrobblerAnimationBegin() {
                return $.ajax();
            }
            function ThrobblerAnimationEnd() {
            }
            $(document).ready(function () {
                function DrawVehicleCostPerDays() {
                    var $deferred = $.Deferred();  //$.Deferred.done() --> to allow ayschronous sleep/delay until this current function() is finish before running done() afterward to continue. [[http://stackoverflow.com/questions/12116505/wait-till-a-function-is-finished-until-running-another-function]]... 

                    $deferred.resolve();
                    return $deferred;
                }

                //Load the script...
                ThrobblerAnimationBegin().done(function () {
                    //alert("done");
                    DrawVehicleCostPerDays(
                        ).done(function () { ThrobblerAnimationEnd(); /*alert('success');*/ }
                        ).fail(function () { ThrobblerAnimationEnd(); /*alert('failed');*/ });
                });
            });
        </script>
    </head>
    <body>

    </body>
</html>

按要求编辑这是来自 Firefox 的 Firebug 的快照。

【问题讨论】:

  • 检查浏览器开发者控制台的网络选项卡,查看实际发出了多少请求。
  • 在编辑部分查看图片快照。
  • 第一次获取在 jquery 之前的事实看起来很可疑。我在您的代码中看不到任何会导致 ajax 发生两次的内容。
  • 我将网页转换为纯 html 并重新检查 firefox 的 firebug 并显示相同的结果。顺便问一下,为什么我的帖子是-1?
  • 您的 ajax 调用的页面是否与调用它的页面相同?换句话说,zz1.cshtml 是您在上面提供的代码吗?

标签: javascript jquery ajax


【解决方案1】:

您的 ajax 没有触发两次。相反,您看到的是初始页面加载(您算作第一个 ajax 请求),然后是 ajax 请求(您算作第二个)。由于您没有在 .ajax() 调用中指定 URL,因此它向同一页面发出了请求,这可能会让您感到困惑。

您应该阅读.ajax() documentation 以了解如何使用它的简单示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 2023-01-24
    • 2013-08-02
    • 2023-03-31
    相关资源
    最近更新 更多