Django jquery ajax 403 error

匿名 (未验证) 提交于 2019-12-03 08:41:19

问题:

I am trying to get ajax to work, but I keep getting a 403 error. I am quite new to jquery.

The following is my code

    $('#prod_search_button').click(function(){     if ($('#inv_prod_list').length) {         //insert a new record     }     else     {         //create the #inv_prod_list table and insert first record         var inv_table= '<table id="inv_prod_list" style="border: 2px solid #dddddd;"></table>';          // create query object         var prod_query = {             query: jQuery.trim($('#id_prod_query').val())         };          // convert object to JSON data         var jsonQuery = JSON.stringify(prod_query);          $.ajax({             type: 'POST',             url: '/company/product/item_search.json/',             data: jsonQuery,               success: function(jsonData){                     var parsed = JSON.parse(jsonData);                     $('#inv_prod_wrap').html(inv_table);                      var new_record = 'this is html for new row'                      $('#inv_prod_list tr:last').after(new_record);                        //off rows alt color                    }         });     } });

回答1:

I think you don't pass CSRF token.



回答2:

You can avoid the CSRF by adding the following annotation before your method definition.

from django.views.decorators.csrf import csrf_exempt  @csrf_exempt def Method():


回答3:

just copy that piece of code from the official docs into a js file and include it in your html

// using jQuery function getCookie(name) {     var cookieValue = null;     if (document.cookie && document.cookie !== '') {         var cookies = document.cookie.split(';');         for (var i = 0; i < cookies.length; i++) {             var cookie = jQuery.trim(cookies[i]);             // Does this cookie string begin with the name we want?             if (cookie.substring(0, name.length + 1) === (name + '=')) {                 cookieValue =   decodeURIComponent(cookie.substring(name.length + 1));                 break;             }         }     }     return cookieValue; } var csrftoken = getCookie('csrftoken'); function csrfSafeMethod(method) {     // these HTTP methods do not require CSRF protection     return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({     beforeSend: function(xhr, settings) {         if (!csrfSafeMethod(settings.type) && !this.crossDomain) {             xhr.setRequestHeader("X-CSRFToken", csrftoken);         }     } });


回答4:

See the HTTP/1.1 Status Code Definitions. "403" is the status code "Forbidden". This is an error being thrown on the server side of your $.ajax request, not the client side (i.e. your code is making a request, but the response from the server is an error message).

The document indicates servers should respond with that error only in specific situations:

The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Typically, an error of this sort means that whatever user you're logged in as does not have access to the URL you are requesting. Often, this indicates that the only error in your code is the URL you are making the request to or the ordering of a sequence of calls (e.g. you are trying to request data before logging in). Less commonly, some web servers and web applications are configured to respond with 403 error codes instead of 404 (not found) error codes for all "invalid" requests to avoid leaking information about what files do/don't exist on the server.



回答5:

I ran into this and figured I'd post what was going on. I had the {% CSRF_TOKEN %} in a cached paged and it was caching what it put there. So for some users it was valid and some it wasn't depending on the cache! It was a nightmare to track down even though it should have been obvious... So check your caching.



回答6:

Can also check if csrf middleware is enabled in settings.py and disable it. Look for 'django.middleware.csrf.CsrfViewMiddleware'.



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