Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 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 Answer

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
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...