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

vijayscode

我试图在.to中创建待办事项列表。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>
vijayscode

现在终于得到了答案,由于id问题,删除列表不起作用,因为存在多种形式的同一个id。这里是更新的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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用$ timeout删除数组中的元素无法正常工作

来自分类Dev

ajax中的ajax无法正常工作

来自分类Dev

删除表中的行无法正常工作

来自分类Dev

删除列在 jquery 中无法正常工作

来自分类Dev

从链表中删除节点无法正常工作

来自分类Dev

使用PHP删除无法正常工作

来自分类Dev

inArray在ajax响应中无法正常工作

来自分类Dev

使用ajax登录无法正常工作

来自分类Dev

Ajax无法正常工作

来自分类Dev

Ajax无法正常工作

来自分类Dev

Ajax 无法正常工作

来自分类Dev

时区在Django中无法正常工作

来自分类Dev

分页在Django中无法正常工作

来自分类Dev

不同的方法在 Django 中无法正常工作

来自分类Dev

Django 1.9 + django-cors-headers + AJAX无法正常工作

来自分类Dev

Django:Ajax POST发送对象数组的数据无法正常工作

来自分类Dev

Django + Jquery + Ajax + D3无法正常工作

来自分类Dev

使用htaccess从子文件夹中删除index.php无法正常工作

来自分类Dev

我无法删除图像,但使用 Flask 在同一目录中插入工作正常

来自分类Dev

级联删除无法正常工作

来自分类Dev

删除功能无法正常工作

来自分类Dev

删除字符无法正常工作

来自分类Dev

删除ChildFragmentManager无法正常工作

来自分类Dev

使用Ajax加载内容时,对话框模式中的图像预览无法正常工作

来自分类Dev

yiii中依赖下拉列表中的ajax无法正常工作

来自分类Dev

Ajax无法在Django中工作吗?

来自分类Dev

CodeIgniter Ajax无法正常工作

来自分类Dev

PHP Ajax无法正常工作

来自分类Dev

AJAX教程无法正常工作