How to insert javascript into an AJAX Django app?
I have a Djang开发者_如何学Co app where the main content changes frequently via AJAX loads. Since I need to run a lot of javascript on the newly loaded content, what I do now is include a javascript block with several document.ready and other functions at the end of the loaded HTML template.
Is this the proper way to load javascript on AJAX loaded content? If I replace the content block with new (AJAX loaded) HTML + scripts, will the old scripts be removed cleanly?
Are there monitoring tools to detect javascript / memory usage? I am running into some page crashes so I suspect there are some leaks occurring.
Thanks!
You should definitely look into using .live()
rather than including new javascript blocks within the loaded html content:
http://api.jquery.com/live/
From the docs:
The .live() method is able to affect elements that have not yet been added to the DOM through the use of event delegation: a handler bound to an ancestor element is responsible for events that are triggered on its descendants.
IMHO you should avoid inserting javascript code into AJAX loading page elements. It's not he best way to do that. Why cant you make a javascript function and activate it after AJAX finishes load? Or put it on click or hover event...
JavaScript Onclick:
<a class="orange"
onclick="return voteClick(this, '{{ item.pk }}', '1', '{% url ajaxvote %}')"
href=''>Button text</a>
and then in your script:
function voteClick(self, pk, multiplier, url){
//some actions function makes
//for e.g. making POST or changing DOM
// you can use vars that are generated by django template system
return false;
};
jQuery Way:
$.post(url, { param1: value1, param2: value2 }, function(data){
//some function actions upon your AJAX complete
//call your function with code here
// you can load some 'data' for this script from django
// and not the whole script
voteClick(self, value1, value2, data);
return false;
} //end function
);//end POST
ou can read more on this: jQuery POST
So main idea here is that you must load script as a static content from your MEDIA_ROOT and pass it some needed parameters. It's hard way to load your scripts with live() functions. You must take care of tracing lot's of functions and params.
Of course if you're using jQuery it's easy to trace code events with it's selectors. But again... Why do you need to load code with AJAX request? It's definitely static file to be used here, as your scripts file...
精彩评论