weixin_33695450 2015-11-22 01:54 采纳率: 0%
浏览 39

通过Ajax与Django一起发布

Based in https://godjango.com/18-basic-ajax/ i trying POST via Ajax and Django.

I create a project on the GitHub https://github.com/rg3915/front-dj-test

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

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

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

<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:

enter image description here

I wonder what needs to be corrected to work everything perfectly.

  • 写回答

2条回答 默认 最新

  • weixin_33697898 2015-11-22 04:39
    关注

    you need

    from django.views.decorators.csrf import csrf_exempt
    
    @csrf_exempt
    def customer_save(request):
        # ...
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab有关常微分方程的问题求解决
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable