使用ajax删除在django中无法正常工作

时间:2015-06-29 21:47:05

标签: python ajax django

我正在尝试在django中构建一个待办事项列表。我想要添加新任务并删除仅使用AJAX执行的已完成任务。 添加功能工作正常,但是当我从底部删除列表时AJAX无法正常工作,有时我能够在页面重新加载后看到JSON数据,有时我会得到

  

“您通过POST调用此URL,但URL不以斜杠结尾”

这个错误。当我从顶部删除列表然后它正常工作.thanx

这是我的代码

models.py

class todoModel(models.Model):
    title = models.CharField(max_length=100)
    added = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title
forms.py

from django.forms import ModelForm
from todoApp.models import todoModel
from django import forms

class todoModelForm(forms.ModelForm):
    class Meta:
        model=todoModel

views.py

# Create your views here.
import json
from django.shortcuts import render_to_response,HttpResponse,redirect
from django.template import RequestContext
from django.shortcuts import render,get_object_or_404
from django.forms import ModelForm
from .forms import todoModelForm
from todoApp.models import todoModel
from django.contrib import messages
from django.core import serializers


def home(request):
    todo=todoModel.objects.all()
    form = todoModelForm()
    return render(request,'index.html',{'form':form,'todo':todo})

def todoPost(request):
    if request.method == 'POST' and request.is_ajax():  #if the form has been submitted
        form = todoModelForm(request.POST)
        if form.is_valid():
            form.save()
        todo_json = serializers.serialize('json',todoModel.objects.all())
        return HttpResponse(json.dumps(todo_json),content_type="application/json")
    return HttpResponse("status")


def delete(request,id):
    if request.method == "POST" and request.is_ajax:
        del_object = get_object_or_404(todoModel ,pk = id)
        del_object.delete()
        todo_json = serializers.serialize('json',todoModel.objects.all())
        return HttpResponse(json.dumps(todo_json),content_type="application/json")
    return HttpResponse("status")

的index.html

<form method="post" id="form_id" action="/post/">
    {% csrf_token %} {{form.as_p}}

    <input type="submit" value="submit" />
</form>

<ul class="todo-div">
    {% for i in todo %}
    <form method="POST" action="delete/{{i.id}}/" id="delForm">
        {% csrf_token %}
        <li>{{i.title}}
            <br/> Created at {{i.added}}
            <br/>Last updated {{i.updated}}</li>
        <input type="submit" value="delete">
        <br/>
        <br/>
    </form>
    {% endfor %}
</ul>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
    $(document).ready(function() {
        $("#form_id").submit(function(e) {
            alert("sad");
            e.preventDefault();
            $.ajax({
                data: $(this).serialize(),
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                dataType: 'json',
                success: function(json) {
                    var jsonData = $.parseJSON(json);
                    var content = "";
                    for (i = 0; i < jsonData.length; i++) {
                        var id = jsonData[i].pk;
                        var title = jsonData[i].fields.title;
                        var added = jsonData[i].fields.added;
                        var updated = jsonData[i].fields.updated;
                        content += "<form method='POST' action='delete/" + id + "'/ id='delForm'>{% csrf_token %}<li><br/>" + title + "<br/>Created at" + added + "<br/>Last updated" + updated + "</li><input type ='submit' value='delete'></form>";
                    }

                    $(".todo-div").empty().append(content);
                },
                error: function(e, x, r) {
                    console.log(e);
                },
            });
        });
    });
</script>
<script>
    $(document).ready(function() {
        $("#delForm").submit(function() {
            event.preventDefault();
            $.ajax({
                data: $(this).serialize(),
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                dataType: 'json',
                success: function(json) {
                    $(".todo-div").empty();
                    var jsonData = $.parseJSON(json);
                    var content = "";
                    for (i = 0; i < jsonData.length; i++) {
                        var id = jsonData[i].pk;
                        var title = jsonData[i].fields.title;
                        var added = jsonData[i].fields.added;
                        var updated = jsonData[i].fields.updated;
                        content += "<form method='POST' action='delete/" + id + "/' id='delForm'>{% csrf_token %}<li><br/>" + title + "<br/>Created at" + added + "<br/>Last updated" + updated + "</li><input type ='submit' value='delete'></form>";
                    }

                    $(".todo-div").append(content);
                },
                error: function(e, x, r) {
                    console.log(e);
                },
            });
        });
    });
</script>

</body>

2 个答案:

答案 0 :(得分:0)

你在第一个javascript代码块中出错:

<script>
    $(document).ready(function() {
        $("#form_id").submit(function(e) {
            alert("sad");
            e.preventDefault();
            $.ajax({
                data: $(this).serialize(),
                type: $(this).attr('method'),
                url: $(this).attr('action'),
                dataType: 'json',
                success: function(json) {
                    var jsonData = $.parseJSON(json);
                    var content = "";
                    for (i = 0; i < jsonData.length; i++) {
                        var id = jsonData[i].pk;
                        var title = jsonData[i].fields.title;
                        var added = jsonData[i].fields.added;
                        var updated = jsonData[i].fields.updated;
                        content += "<form method='POST' action='delete/" + id + "'/ id='delForm'>{% csrf_token %}<li><br/>" + title + "<br/>Created at" + added + "<br/>Last updated" + updated + "</li><input type ='submit' value='delete'></form>";
                        ---single quote before slash--->--->--->--->-------------^
                    }

                    $(".todo-div").empty().append(content);
                },
                error: function(e, x, r) {
                    console.log(e);
                },
            });
        });
    });
</script>

答案 1 :(得分:0)

现在终于得到了答案,删除列表因为id问题而无法工作,因为有多种形式的相同id.Here是更新的html。

<form method="post" id="form_id" action="/post/">
 {% csrf_token %} 
{{form.as_p}}

<input type="submit" value="submit"/>
</form>

<ul class="todo-div">
{% for i in todo %}
<form method="POST" action="/delete/{{i.id}}/" id="{{i.id}}">
{% csrf_token %}
<li>{{i.title}}
<br/>
Created at {{i.added}} 
<br/>Last updated {{i.updated}}</li> 
<input type ="submit" value="delete" class="deletebutton" onclick=delete_form({{i.id}})>
<br/><br/>
</form>
{% endfor %}
</ul>
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>

  $("#form_id").submit(function(e)
  {

      e.preventDefault();
      $.ajax({
             data:$(this).serialize(),
             type:$(this).attr('method'),
             url:$(this).attr('action'),
             dataType:'json',
             success:function(json)
              {
              alert("List added Successfully");
              var jsonData=$.parseJSON(json);
              var content="";
              console.log(jsonData)
                for(i=0;i<jsonData.length;i++)
                {
                  var id=jsonData[i].pk;
                  var title = jsonData[i].fields.title;
                  var added = jsonData[i].fields.added;
                  var updated = jsonData[i].fields.updated;
                  content +="<form method='POST' action='/delete/" +id + "/' id="+id+">{% csrf_token %}<li><br/>"+title+"<br/>Created at"+ added  +"<br/>Last updated"+updated +"</li><input type ='submit' onclick=delete_form("+id+") class='deletebutton' value='delete'></form>";
                }

                 $(".todo-div").empty().append(content);
              },
            error:function(e,x,r)
             {
              console.log(e); 
             },
        });
  } );

</script>
<script>

  function delete_form(id){
  var id=id;
  var ele = document.getElementById(id)
  //var form = $(ele).serialize()
  //alert(form);
$(ele).submit(function(e)
  {

     event.preventDefault();

      $.ajax({
             data:$(ele).serialize(),
             type:$(ele).attr('method'),
             url:$(ele).attr('action'),
             dataType:'json',
             success:function(json)
              {
              alert("List removed Successfully");
              $(".todo-div").empty();
              var jsonData=$.parseJSON(json);
              var content="";
                for(i=0;i<jsonData.length;i++)
                {
                  var id=jsonData[i].pk;
                  var title = jsonData[i].fields.title;
                  var added = jsonData[i].fields.added;
                  var updated = jsonData[i].fields.updated;
                  content +="<form method='POST' action='/delete/" +id + "/' id="+id+">{% csrf_token %}<li><br/>"+title+"<br/>Created at"+ added  +"<br/>Last updated"+updated +"</li><input type ='submit' onclick=delete_form("+id+") class='deletebutton' value='delete'></form>";
                }

                 $(".todo-div").append(content);
              },
            error:function(e,x,r)
             {
              console.log(e); 
             },
        });
  });
  }
</script>