how does jquery and ajax go together?
Here is my situation:
i have a page once clicking on one of it's divs an ajax request fetches more content to the page.
The more content that i am talking about is image gallery content that uses jQuery.
my probl开发者_如何学Pythonem is that once i get the response from the ajax request, i manipulate the DOM.
therefore the jquery ready() function is not available to me anymore (or is it ?)
to skip the problem i assigned a function to the
$.fn
called InitGallery
.
Using eval
i can call it once my ajax response arrives and all is fine except one small issue- synchronization!
Once i eval
my $.fn.InitGallery
code, the manipulated DOM is not necessarily fully loaded, and therefore my InitGallery fails.
Once i add a sleep, or alert to my code, and make sure that the InitGallery function runs after the DOM is ready again, it's fine and working.
i guess my question is how can i re assign a ready function to the DOM ? how can i make sure that the function i call after the ajax response gets called only after the changes the ajax response did on the DOM are ready ? thank you
You have a couple options depending on what you're trying to do.
If you use the live
function, you can wire your events up once and they will continue to work after you've changed the DOM.
Another option is to put the initialize code in a function:
$(function() {
doCoolStuff();
});
Then hook up to the ajaxComplete
or ajaxSuccess
event:
$.ajaxComplete(function() {
doCoolStuff();
});
I need more information but my preliminary answer is:
Whatever loads your content ajax should trigger a "ready" event or something similar on the new content is done loading. That way you could bind your InitGallery to "ready" on that element and do all of your initialization after the dom is ready.
What is loading your content via AJAX?
put the call to your init function in the success handler of your ajax request.
$.ajax({
url: 'ajax/test.html',
success: function(data) {
makeYourChanges();
callYourInit();
}
});
No need to use the ready()
event on the document again for this. the ready event fires only once, when the DOM has initially loaded.
The approach for this is to assign a function to the success
property of the object that you pass to the ajax
call; This is the function that you want to be executed once the response from the call has successfully completed.
$.ajax({
url : 'http://some.url',
success : function(response) {
// do the insert into the DOM. An example
// assuming your response is text/html
$(document.body).append(response);
// now call InitGallery
$('#selector').InitGallery();
}
});
I advise you to use tools for Ajax Debugging like firebug or the recent firequery.
精彩评论