javascript - 通过带有参数的javascript调用django url
问题描述
这是我传递参数的javascript函数,使用警报我检查了该函数是否正在获取我想要的参数,但我无法在django url中传递它们,否则给出一个url有效但不带参数的字符串。
function myFunction(a) {
var v = a.value;
alert(v);
location.href="{% url 'new_event' v %}"; //does not works
location.href="{% url 'new_event' 'string' %}"; //works
}
我已经检查了获取的值是我想要的字符串但是如何传递它?
解决方案
请试试这个:
function myFunction(a) {
var v = a.value;
alert(v);
location.href="{% url 'new_event' v %}"; // this will not work because your django **url** filter is pre-processed on your server while your javascript variable is processed on **client**
// if you want your variable v to be dynamic, you need to include it in your django's view **context**
location.href="{% url 'new_event' 'string' %}"; //works
}
// include in your views.py
context['v'] = 'some-string'
// template.html
<script>
function myFunction(a) {
var v = '{{ v }}'; // javascript variable v
alert(v);
location.href="{% url 'new_event' v %}"; // django context variable v
}
</script>
推荐阅读
- javascript - 编译代码中的错误未在使用 mongodb 的 nodejs 中显示任何特定错误
- c# - 如何使用 c# 的 SqlCommand 获取 IDENT_CURRENT 结果?
- html - 如何使用父标签中的样式强制所有标签?
- c++11 - 将 RepeatedPtrField 分配给 protobuf 消息中的重复字段
- vbscript - 如何在不显示错误的情况下运行脚本
- kubernetes - Kubernetes HPA 在缩减期间杀死随机 pod | 无论如何,为了避免杀死一个随机的 pod,而不是去使用低利用率的 pod
- php - 这是我在 laravel 数据库中插入多条记录的代码。那么,它不起作用吗?有人帮我吗?
- linux - 如何从文件名中删除日期linux
- mongodb - 如何在 Mongo DB 中合并文档数组
- jquery - 元属性 og:图像在 whatsapp 中不起作用