call javascript function from django

10,172

Solution 1

If you're talking about in-browser js, no, django cannot call a javascript function. You've got django running on your server, and js running in the user's browser, and never the two shall mingle. Imagine if any old django site out there could reach into your browser at will and start doing things you didn't ask for!

What you can do is setup some sort of communication between the two, aka AJAX. Have the javascript side periodically poll the django server for information, at which point django can tell the javascript what to do (do this function, run that process). Or figure out how to do comet.

OTOH, If you're talking about server-side js, sure, why not? It'd be the same as calling a perl function, or a ruby function (feed the interpreter the correct instructions to import/define/call that function).

Solution 2

No. The Django view is called by a request of a User to an Url. It is possible that this is a Javascript-Call, but javascript cannot be called from Django, sorry.

Solution 3

A response returns stuff to the browser - if that stuff contains javascript in the usual way then yes. Just return some HTML with a script tag and the usual javascript.

It's not clear that's what you want to do though...

Solution 4

In addition to JS in templates you can use async (AJAX) calls to communicate with the server. This allows you to call Django funcs at your views without too much hassle.

Share:
10,172
Rajeev
Author by

Rajeev

Updated on June 04, 2022

Comments

  • Rajeev
    Rajeev almost 2 years

    Can a javascript function be called from django HttpResponseredirect or some other django function

  • Trix
    Trix about 9 years