Ajax不传输数据

时间:2017-01-04 09:37:19

标签: ajax django csrf-protection

我正在使用ajax将数据传递到视图以便在数据库中保存。 在javascript中,数据看起来正确但在视图中为null。 阅读代码中的注释以获取其他问题和信息

我的javascript

...
var changed_element=[];
var changed_value=[];

document.getElementById('tabella').addEventListener('change', function(event){
    ...
    changed_element.push(element); //list of list of string
    changed_value.push(elem[elem.value].text); //list of string
    ...
});

document.getElementById('btn-save').addEventListener('click', function() {
  console.log('changed_element', changed_element) //print the right value
  $.ajax({type: 'POST',
    url: '/salva-conoscenze-rapporti/',
    data: {
      changed_element: changed_element,
      changed_value: changed_value //<= comma?
    },
    success: function(msg) {
      console.log(msg) //prints 'It works'
      document.getElementById('btn-save').style.display = 'none';
    } //<= comma?
  });
});

我的view

@staff_member_required
@ensure_csrf_cookie #I need this?
def salva_conoscenze_rapporti(request):
    if request.is_ajax():
        changed_element = request.POST.get('changed_element', None)
        changed_value = request.POST.get('changed_value', None)
        msg='it works'
        print(changed_element) #prints None instead of array
        print(changed_value)

    else:
        msg="it doesn't work"
    return HttpResponse(msg)

我的template base.html

...
<script>
  var csrftoken = $.cookie('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);
      }
    }
  });
</script>
...

我的template

{% extends 'base.html' %}
...

基本上print(changed_element)应该提供数据而不是None

MIDDLEWARE_CLASSES中的settings.py

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

我的变数:

changed_element=[ [ "conoscenza", "Cliente1", "Cliente2" ] ];

changed_value=[ "Generale" ];

console.log(changed_element)提供:Array [ Array[3] ]

1 个答案:

答案 0 :(得分:0)

要获取cookie,您也可以使用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');

然后,我会纠正你的剧本。

// $('.btn-save').click(function() { // to simply with jquery
document.getElementById('btn-save').addEventListener('click', function() {
  $.ajax({
    type: 'POST',
    url: '/salva-conoscenze-rapporti/',
    data: {
      "changed_element"    : changed_element,
      "changed_value"      : changed_value,
      "csrfmiddlewaretoken": csrftoken // from `var csrftoken;`
    },
    success: function(msg) {
      console.log(msg) //prints 'It works'
      document.getElementById('btn-save').style.display = 'none';
    } //<= comma?
  });
});

或者喜欢这个:

$('.btn-save').click(function() {
  var form = new FormData();
  form.append('changed_element', changed_element);
  form.append('changed_value', changed_value);
  form.append('csrfmiddlewaretoken', getCookie('csrftoken'));

  $.ajax({
    type: 'POST',
    url: '/salva-conoscenze-rapporti/',
    data: form,
    processData: false,
    contentType: false,
    success: function(msg) {
      console.log(msg) //prints 'It works'
      document.getElementById('btn-save').style.display = 'none';
    }
  });
});

views.py

from django.views.decorators.csrf import csrf_protect

@csrf_protect
@staff_member_required
def salva_conoscenze_rapporti(request):
    if request.method == 'POST' and request.is_ajax():
        changed_element = request.POST.get('changed_element', None)
        changed_value = request.POST.get('changed_value', None)
        msg = 'it works'
        print(changed_element)
        print(changed_value)
    else:
        msg="it doesn't work"
    return HttpResponse(msg)

希望它可以提供帮助。