django-Ajax 对某些按钮点击不起作用

django-Ajax Does not work on some button clicks

我有一个网页,其中包含使用 django.Using ajax 生成的多个按钮,当我单击一个按钮时,将值发送到服务器 randomly.The 按钮值根据传递的值设置通过来自 django.Heres 代码的上下文:

<button name="date" type="submit" value={{d}} ">
            

Ajax代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> 
</script>
<script>
     function sendData(event){
     event.preventDefault();
     $.ajax({
     type : "POST", 
     url: "",
     data: {
       date : event.target.value,
        csrfmiddlewaretoken:'{{ csrf_token }}',

     },
     success: function(data){
             
            },
     
            failure: function() {
                
            }

      });
    }
  </script>

当我尝试在 views.py 上打印 request.POST 时,它有时只显示 csrftoken 而不是同时显示日期和 csrftoken,我尝试在成功函数中给出警告框,并且总是在以下情况下弹出警告我点击了一个按钮,即使只有 csrf 令牌被传递到服务器 提前致谢

你可以这样完成工作

<button type="submit" onclick="return sendData('{{d}}')">
  <p>{{y}}</p>
  <p class="card-text">{{d}}</p>
</button>

为了看起来干净,我删除了一些代码,您可以稍后添加

function sendData(date){
  $.ajax({
    type : "POST", 
    url: "",
    data: {
      date : date,
      csrfmiddlewaretoken:'{{ csrf_token }}',
    },
    
    success: function(data){
      
    },
    failure: function() {
      
    }
    
  });
  return false
}

我建议不要在循环中使用 id 因为它重复相同的 id 多次

The id attribute specifies its element's unique identifier (ID). The value must be unique amongst all the IDs in the element's for more info check this