【问题标题】:jquery custom events return valuejquery自定义事件返回值
【发布时间】:2012-05-14 20:20:20
【问题描述】:

我正在尝试了解有关 jquery 自定义事件的更多信息,因此我编写了这个简单的代码来进行测试:

<!DOCTYPE html>
<html>
    <head>
        <title>Jquery custom events</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
        <script>
            $(function(){
                $('#link1').click(function(){
                    var that = $(this);
                    $.ajax({
                        url: "http://localhost/jquery/index.html",

                        beforeSend: function(event){ // if returned false, stops ajax request
                           return that.trigger('ajax:beforesend',[{p1: '1'},{p2: '2'}]);

                        },
                        success: function(){
                            that.trigger('ajax:success');
                        },
                        error: function(){
                        }
                    });

                    return false;
                });

                $('#link1').bind('ajax:beforesend',function(e,data,data2){
                    alert("success"+data2.p2);
                    return false;
                });

                $('#link1').bind('ajax:success',function(e){
                    alert("success");

                });
            });
        </script>
    </head>

    <body>
        <a id="link1">link1</a>

        <div id="box" style="width:500px;height:150px;background-color: gray;margin-top: 50px;">
            result
        </div>
    </body>

</html>

我的问题是:在 beforesend 函数中,如果触发的自定义事件的结果为 false 但不起作用,我想中止 ajax 请求, 我错过了什么?

编辑:请不要专注于发送前功能。我真正想要的是如何将自定义事件结果(例如真或假)返回到调用事件的位置(在这种情况下是在发送函数之前)。正如我所说,这只是样板代码。不是真实世界的项目。

【问题讨论】:

  • 为什么不先检查自定义事件的结果,如果是真的,启动ajax请求..
  • 根据我的经验,beforesend 很少需要。
  • sha404,如何查看自定义事件的结果?

标签: jquery return custom-events


【解决方案1】:

beforeSend 是一个 Ajax 事件。在 beforeSend 函数中返回 false 将取消请求。从 jQuery 1.5 开始,无论请求的类型如何,都将调用 beforeSend 选项。

请在此处检查 beforesend ajax 事件处理程序并尝试http://api.jquery.com/jQuery.ajax/

很可能您的问题在于beforesend 函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-05
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 2022-07-16
    相关资源
    最近更新 更多