开发者

jQuery: Firing an AJAX event local to the element that is loading data

开发者 https://www.devze.com 2023-01-11 16:30 出处:网络
I\'ve been playing around with subscribing elements to AJAX events in jQuery. I have an element that I am using to load AJAX response\'s. This element is only displayed IF there is data pertinent to

I've been playing around with subscribing elements to AJAX events in jQuery.

I have an element that I am using to load AJAX response's. This element is only displayed IF there is data pertinent to the current context of the program.

So, I thought it would be nice and easy to .show() whenever an AJAX request has completed on it and hide it when I need to. I would like to remove the need to implicitly .show() the element every time I make an AJAX request.

In jQuery there is .ajaxSuccess() and .ajaxComplete(). These however, will fire when any AJAX request completes/succeeds, so when loading data in other parts of the page, my hidden element will .show().

The solution seems to be (per. the jQuery API reference) to use the ajaxOptions parameter in your event handler function:

$('.log').ajaxComplete(function(e, xhr, settings) {
  if (settings.url == 'ajax/test.html') {
    $(this).text('Triggered ajaxComplete handler.');
  }
});

What I don't understand is the reason for registering an event handler for all AJAX requests to a specific element, besides being able to use $(this). Am I missing something, can I register an event handler for an AJAX request specific to an element?

If not, is there any event driven alternative to using the .url? The reason I ask is that I use the page fragment extensively for tracking page state and it would be easier to have an event handler .show() my element whenever an AJAX request开发者_高级运维 loads data into it.

EDIT: Post title grammar.


My thinking, is that you want something like this:

$(document).ajaxComplete(function(e, xhr, settings) {
    if(settings.url == 'ajax/test.html') {
      $('#foo').text('Triggered ajaxComplete handler.');
    } else if(settings.url == 'ajax/another.html') {
      $('#bar').text('Triggered ajaxComplete handler.');
    }
});

Does that make sense, or am I completely missing the point?


Bind a global event handler to AJAX requests and then use the event target member to decide to show elements:

$(document).ajaxSuccess(function (event, xhr, settings) {
    if ($(event.target).is('#main'))
        $('#main').show();
});

Would be nice to be able to fire on AJAX requests that only target specific elements, but there doesn't seem to be a way.

EDIT: Syntax

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号