简体   繁体   English

通过Ajax与Django一起发布

[英]POST via Ajax with Django

Based in https://godjango.com/18-basic-ajax/ i trying POST via Ajax and Django. 基于https://godjango.com/18-basic-ajax/我尝试通过Ajax和Django进行POST。

I create a project on the GitHub https://github.com/rg3915/front-dj-test 我在GitHub https://github.com/rg3915/front-dj-test上创建了一个项目

urls.py urls.py

url(r'^customer/add$', 'core.views.customer_add', name='customer_add'),
url(r'^customer/save$', 'core.views.customer_save', name='customer_save'),

models.py models.py

class Customer(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField()

views.py views.py

import json
from django.shortcuts import render
from django.http import Http404, HttpResponse


def customer_add(request):
    return render(request, 'customer_add.html')


def customer_save(request):
    if request.is_ajax() and request.POST:
        # return HttpResponse('Salvou')
        data = {'message': "%s added" % request.POST.get('item')}
        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        raise Http404

customer_add.html customer_add.html

<html>
  <body>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <form class="form-horizontal col-sm-4 col-lg-4" method="POST">
    <legend>Cadastrar</legend>
    {% csrf_token %}

    <div class="form-group">
      <label for="id_name">Nome</label>
      <input type="text" id="id_name" name="name" class="form-control">
    </div>

    <div class="form-group">
      <label for="id_email">e-mail</label>
      <input type="text" id="id_email" name="email" class="form-control">
    </div>

    <div class="form-group">
      <div class="col-sm-10 col-sm-offset-2">
      <button type="submit" id="id_submit" class="btn btn-primary">Salvar</button>
      </div>
    </div>
  </form>

  <script>
    $('form').submit(function(event) {
      console.log($( "form" ).serializeArray());
      $.ajax({
        type: 'POST',
        url: '/customer/save',
        data: {"item": $("input").val()},
        dataType: 'json',
        encode: true,
        crossDomain: false,
        beforeSend: function(xhr, settings) {
          if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
        },
        success: function(data){
          console.log(data);
        },
        error: function(){
          // alert('Deu Erro');
          console.log('Deu Erro');
        }
      });
      event.preventDefault();

      // CSRF code
      function getCookie(name) {
        var cookieValue = null;
        var i = 0;
        if (document.cookie && document.cookie !== '') {
          var cookies = document.cookie.split(';');
          for (i; 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));
      }
    });
  </script>

  </body>
</html>

But this giving some errors. 但这给了一些错误。 See the picture next: 参见下图:

在此处输入图片说明

I wonder what needs to be corrected to work everything perfectly. 我想知道什么需要纠正才能完美地工作。

you need 你需要

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def customer_save(request):
    # ...

Your are doing it wrong. 你做错了。 You send an undefined crsftoken because you define your crsftoken value after the request : var csrftoken = getCookie('csrftoken'); 您发送未定义的crsftoken因为您在请求之后定义了crsftoken值: var csrftoken = getCookie('csrftoken');

With your solution corrected : 解决了您的问题:

function getCookie(name) {
  var cookieValue = null;
  var i = 0;
  if (document.cookie && document.cookie !== '') {
    var cookies = document.cookie.split(';');
    for (i; 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;
}
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$('form').submit(function(event) {
    event.preventDefault();
    console.log($( "form" ).serializeArray());
    $.ajax({
        type: 'POST',
        url: '/customer/save',
        data: {"item": $("input").val()},
        dataType: 'json',
        encode: true,
        crossDomain: false,
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('crsftoken'));
            }
        },
        success: function(data){
            console.log(data);
        },
        error: function(){
            // alert('Deu Erro');
            console.log('Deu Erro');
        }
    });
});

You can also send the CRSF token in the data object. 您也可以在data对象中发送CRSF令牌。 You handle crsftoken like other fields then you don't need no more of getCookie csrfSafeMethod functions. 您像处理其他字段一样处理crsftoken则不需要更多的getCookie csrfSafeMethod函数。 Here is an example : 这是一个例子:

// replace with the correct CSS selector of your crsftoken input
var crsftoken = $('input[name=\'crsftokenmiddleware\']').val()
$.ajax({
    type: 'POST',
    url: '/customer/save',
    data: {
      'crsftokenmiddleware': crsftoken
      'item': $("input").val()
    },
    dataType: 'json',
    encode: true,
    crossDomain: false,
    success: function(data){
        console.log(data);
    },
    error: function(){
        // alert('Deu Erro');
        console.log('Deu Erro');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM