如何将csrf_token传递给django中的javascript文件? [英] how to pass csrf_token to javascript file in django?
问题描述
这是我的JavaScript代码,工作正常。但我喜欢保留javascript文件,不能用作内嵌脚本标签。
Here is my javascript code that works fine. but I like to keep javascript files seperate and not use as inline script tags
<script>
$('.book').click(function() {
var id= $(this).attr('id');
data={
'id':id,
'csrfmiddlewaretoken':'{{ csrf_token }}',
};
$.ajax({
url: '/post/book/',
cache:'false',
dataType:'json',
type:'POST',
data:data,
success: function(data){
//do something
else {
//do something
}
},
error: function(error){
alert('error; '+ eval(error));
}
});
return false;
});
});
</script>
我想将这个包含在我的base.html中包含的custom.js文件中。
这是
I want to include this in my custom.js file that I have included in my base.html. which is
{% load static from staticfiles %}
{% load bootstrap3 %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}{% endblock %}</title>
{% bootstrap_css %}
<!-- Optional theme -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
<link href="{% static "css/custom.css" %}" rel="stylesheet">
<!-- Latest compiled and minified JavaScript -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.js"></script>
<script src="{% static "js/custom.js" %}" ></script>
<script src="{% static "js/jquery.blockUI.js" %}"></script>
{% bootstrap_javascript %}
{% load bootstrap3 %}
{% load static from staticfiles %}
{% block content %} {% endblock %}
我无法引用 csrf_token
当前模板在Django到 static js
文件。如何获得这个工作?
I am not able to reference csrf_token
that is available in the current template in Django to the static js
file. how can I get this to work?
推荐答案
如果你想引用模板标签,那么你需要这个文件被模板化)由Django。我不建议通过django来呈现所有的静态文件。
If you want to reference template tags then you need that file to be templated (rendered) by Django. And I wouldn't recommend rendering all your static files via django...
您可以将csrf_token放在一个全局变量中,然后从脚本中访问。在你的base.html中有这样的东西:
You can either put the csrf_token in a global variable that you then access from your script. Something like this in your base.html:
<script>
var csrftoken = '{{ csrf_token }}';
</script>
或者您可以从javascript文件中的cookies中拉出csrftoken。请参阅此问题以获得解决方案。该cookie称为 csrftoken
。您可以通过打开您的开发工具并查看您的域的Cookie来查看它。
Or you can pull the csrftoken from the cookies in your javascript file. See this question for a solution for that. The cookie is called csrftoken
. You can view it by opening up your dev tools and looking at the cookies for your domain.
这篇关于如何将csrf_token传递给django中的javascript文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!