jquery custom events return value

倾然丶 夕夏残阳落幕 提交于 2019-12-24 08:48:54

问题


I am trying to learn more about jquery custom events so I have made this simple code to make tests:

<!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>

My question is: in the beforesend function i want to abort the ajax request if the result of the triggered custom event is false but is not working, What i am missing?

EDIT: Please dont be focus on beforesend function. What i really want is how to return the custom event result (example true or false) to where the event was called (in this case before send function). As I said this is just boilerplate code. Not a real world project.


回答1:


beforeSend is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request.

Please check the beforesend ajax event handler here and try http://api.jquery.com/jQuery.ajax/

Most probably your problem lies within the beforesend function.



来源:https://stackoverflow.com/questions/10463218/jquery-custom-events-return-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!