【问题标题】:Sending href and id of clicked link from page to django using Ajax使用 Ajax 将点击链接的 href 和 id 从页面发送到 django
【发布时间】: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 %}}
  • 但该文档中并没有说要这样做。

标签: jquery django ajax


【解决方案1】:

设法弄清楚:

index.html

$("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: JSON.stringify({"id":id, "href":href}), 
            type: "POST",
            beforeSend: function (xhr, settings) {
                            xhr.setRequestHeader("X-CSRFToken", csrftok);
                        }, 
            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); 
            } 
        }); 
    }
});

其中 csrftok 是一个变量,其值是通过将其添加到 html 中获得的:

{% csrf_token %}
<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(event) { 
        var csrftok = jQuery("[name=csrfmiddlewaretoken]").val();
                    });  
</script>

views.py

def nameOfFunction(request):
    if request.method == 'POST':
        received = ast.literal_eval(request.body.decode())
        id= received['id']
        link= received['link']
    if "https" in link:
        return JsonResponse({'msg': "yes", "href":link})
    else:
        return JsonResponse({'msg': "no", "href":link})

urls.py(添加此代码)

path('nameOfFunction/', views.nameOfFunction)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    相关资源
    最近更新 更多