Reload Document Ready after Ajax Response Injection to the DOM?
I have a form that uses a color picker, this is defined in th开发者_开发知识库e Document Ready
with the form select input tags. But I require to access some data trough AJAX in another page and have the response replace that form. When I do this, the jquery colorpicker stops working. I guess it would be cool to reload the Document Ready
or something.
Otherwise I think my only option is JSON to pass the variables from PHP output to jquery and then back to html, right?
There are two basic ways to accomplish this. The first is to make the function which initializes your color picker callable from other code. The other is to manually retrigger the document's ready event. The former requires a small modification to your color picker code, but the latter will re-execute all functions bound to document.ready! Be sure that's what you want before you do it. :-)
// option one
function setupColorPicker() {
// do color picking magic
}
$(document).ready(setupDatePicker);
$.ajax(options).done(setupColorPicker);
// option two
$(document).ready(function() {
// do color picking magic
});
$.ajax(options).done(function() {
$(document).trigger("ready"); // probably has unintended side-effects!
});
You could make the color picker initializing script run from it's own function and call that once in document ready and again in the callback of your ajax call.
You should register the events using the live
or the delegate
method:
- http://api.jquery.com/live/
- http://api.jquery.com/delegate/
Passing back the data from server as JSON will not only accomplish your goal but will also boost the performance(SPEED) of the application and also save you bytes of bandwidth. If you still want to inject response as plain html simply initialiZe the color picker plugin in a function and call the function after your ajax success callback.
$(document).ready(function(){
//page is ready
function colorpicker(){
//initialize your color picker
}
$.ajax({
url: 'serverpage.cshtml', //whatever server page
data: {data1: data1},
success: function(){
//append the response into the designated form or div
colorpicker(); //fire the color picker function to refresh
}
});
});
精彩评论