Sunday, July 1, 2012

Re: javascript in django template not executed when request is sent via ajax

On Fri, Jun 29, 2012 at 2:45 PM, Larry Martell <larry.martell@gmail.com> wrote:
> I have a django template that has some javascript/jQuery code in it
> that defines some keyup event handers. If a user goes to the URL
> directly the javascript is executed, and the event handers all work
> fine. There is also a field that they can type in that triggers the
> same URL request to be sent via ajax. When they do this, it seems that
> the html is rendered, but the javascript is not executed. I discovered
> this by noticing that the page was rendered, but none of the
> javascript event handers were being called. I proved this by adding:
>
>
>     <script type="text/javascript">
>     alert('here we are');
>     </script>
>
> to the template, and the alert doesn't show when the request comes
> from ajax. But if I go to the URL directly it does.
>
> Is this a known issue? Is there some way I can get my javascript code
> to run to install my event handlers when the request comes from ajax?

Just in case anyone is interested, I finally got this working.

I added a class to the javascript code, e.g.:

<script class='ajax' type="text/javascript">

And then in the ajax success function, added this:

$(html).filter('.ajax').each(function(){
$.globalEval($(this).text())
});

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment