Calling Django View from Ajax

穿精又带淫゛_ 提交于 2019-12-05 08:37:43
chandu

Replace "post" with "ajax" in the code,now the print statement will work in your view.

function request_access($this){
    console.log("button clicked");
    var request_data = $this.id;
    console.log("data: " + request_data);
    $.ajax({
        url: "request_access/",
        data : { request_data: request_data},
        success : function(json) {
            $("#request-access").hide();
            console.log("requested access complete");
        }
    })
}

Difference between $.post and $.ajax?

$.post vs $.ajax

This will return null value.

views.py

def request_access(request):
    print("DJANGO VIEW")
    a = request.POST.get('request_data')
    print a
    return HttpResponse(json.dumps(a),content_type="application/json")

js

function request_access($this){
    console.log("button clicked");
    var request_data = $this.id;
    alert(request_data);
    console.log("data: " + request_data);
    $.ajax({
        type: 'GET',
        url: "/crm/request_access/",
        data : { 'request_data': request_data},
        success : function(json) {
            $("#request-access").hide();
            console.log("requested access complete");
        }
    })
}

I encountered the same problem, i.e my view no errors but my view wasn't called. Here is how I solved it :

I was trying to get the following url :

url(r'users/change_rights', 'change_user_right', name='change_user_right'),

But the users/change_rights url also matched another url I had registered :

url(r'users', 'users_table', name='users_table'),

So django was just calling the first non ajax view and not returning any errors.

To fix it add a '$' at the end of the second url so it will not contain the users/change_rights:

url(r'users$', 'users_table', name='users_table'),

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!