【发布时间】:2019-06-24 16:02:13
【问题描述】:
我有一个点击 JQuery 事件处理程序,我想用它来将任何点击链接的 href 和 id 发送到我的 Django 服务器。但是我很难找到关于将 Django 与 Ajax 结合使用的好教程/信息。
假设我想发送链接的 id 和 href,让 Django 检查链接是否有 https,然后将 href 连同消息一起作为响应发送回来。
类似:
$("a").on("click", function(e){
e.preventDefault();
if(e.target.href){
let id = e.target.id;
let href = e.target.href;
$.ajax({
url: "/nameOfFunction/",
data: {"id":id, "href":href},
type: "POST",
success: function(response) {
if(response.msg=="yes"){alert(response.href+" is Secure")}
else{alert(response.href+" is Not Secure")}
},
error:function(error) {
console.log(error);
}
});
}
});
def nameOfFunction(request):
if ("https" in request.POST.get("href")):
msg = "yes"
else:
msg = "no"
return ({"msg":msg, "href":href})
有人可以帮我解决这个问题吗?
【问题讨论】:
-
这段代码会发生什么?
-
这是我在 Flask 中使用的代码(这是一个更简单的框架)。上面可能不会工作,主要是因为它缺少一些项目,如 csrf 令牌。我也不确定应该以什么形式发送数据。
-
那么,您是否阅读了CSRF in Ajax 上的综合文档?
-
是的,仍然没有多大帮助。我已经在我的 ajax 请求中添加了
csrfmiddlewaretoken: {{% csrf_token %}} -
但该文档中并没有说要这样做。