Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

jquery ajax - global settings. Is it possible to know what event/element trigger the ajax call?

This is easy enough to work around, but it would be nice if it was wrapped up in the global ajax setup

When I run an ajax call, I'd like to know which element/event trigger the ajax call in the beforeSend option.

Is there a concise way of doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The beforeSend callback takes two arguments: the XMLHTTPRequest instance and the settings used by the current AJAX call.

Therefore, if you pass the triggering element and event in the context option, they will be available to beforeSend even if you define it in the global setup:

$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        var element = settings.context.element;
        var event = settings.context.event;

        // Do something with 'element' and 'event'...
    }
});

$("selector").click(function(e) {
    $.ajax("url", {
        // your settings,
        context: {
            element: this,
            event: e
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...