使用Ajax从页面向django发送href的点击链接的ID和ID

时间:2019-06-24 16:02:13

标签: jquery django ajax

我有一个单击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})

有人可以帮我解决这个问题,使其起作用吗?

1 个答案:

答案 0 :(得分:0)

设法弄清楚了

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)