【问题标题】:How to pass the argument to the external javascript via django view如何通过 django 视图将参数传递给外部 javascript
【发布时间】:2015-03-26 15:29:34
【问题描述】:

我想通过 django 视图将参数传递给 javascript。

我总是把js代码和html代码分成两个文件,index.html和index.js。

这里是 django 视图

def index(request):
    template = loader.get_template('index.html')
    context = RequestContext(request,{'name':'guest'})
    return HttpResponse(template.render(context))

我有这样的 index.html

访问index.html中的参数名就可以了。

<!DOCTYPE html>
<meta charset="utf-8">
{% load staticfiles %}
<script> 
var name='{{ name }}'
console.log(name) //guest
</script> 
<script src="{% static "js/index.js" %}"></script>
</body>

但在外部 index.js 中,我无法访问参数。

var name ='{{ name }}'
console.log(name) //'{{name}}'

如何将参数或变量传递给外部 javascript?

谢谢!

【问题讨论】:

  • 你不能!您可以从 html 文件中调用您需要的函数,这样您就可以传递参数,或者您应该将值放在 DOM 中的隐藏元素中,然后从外部 js 文件中读取它

标签: javascript python html django


【解决方案1】:

您已经在 index.html 的脚本块中使 name 变量全局可用。您可以直接在任何其他 JS 中将其引用为 name

【讨论】:

  • 所以我必须在 index.html 中显式地创建一个全局变量?如果我想直接将参数传递给外部 js 文件怎么办?
  • 我不明白你的问题,对不起。
  • 抱歉我的解释,是否可以将参数传递给外部 js 而无需在 html 文件中分配任何全局变量?
猜你喜欢
  • 2012-01-17
  • 1970-01-01
  • 2018-01-17
  • 1970-01-01
  • 2011-04-27
  • 2019-08-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多