django ajax发送post请求的两种方法

yipeiwu_com5年前Python基础

django ajax发送post请求的两种方法,具体内容如下所述:

第一种:将csrf_token放在from表单里

 <script>
    function add_competion_goods() {
      $.ajax({
        url: "{% url 'add_competition_goods' %}",
        type: "POST",
        dataType: "json",
        data: $('#add_competition_goods_from').serialize(),//直接将from表单打包
        success: function () {
          $('#add_competition_modal').modal('hide');
          alert('secces')
        }
      })
    }
  </script>

   第二种:发送前添加头部信息

<script>
    function submit_read_save_order_data() {
      var excel_file = document.getElementById("order_excel").files;
      var excel_file_size = excel_file[0]['size'];
      console.log(excel_file_size);
      if (excel_file_size > 0 & excel_file_size < 60000000) {
        alert("已开始上传");
        $('button#upload_data').attr('disabled', 'disabled');
        {#console.log(excel_file_size);#}
        var fd = new FormData();
        fd.append('excels', excel_file[0]);
        $.ajax({
            url: "{%url 'read_save_order_data' %}",
            type: "POST",
            dataType: "json",
            data: fd,
            processData: false,// tell jQuery not to process the data
            contentType: false,// tell jQuery not to set contentType
            beforeSend: function (xhr, setting) {
              xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}")
            },
            success: function (msg) {
              alert(msg)
            },
            error: function (msg) {
              alert(msg)
             }
          }
        )
      } else {
        alert("文件为空,或大小超出60M,请检查")
      }
    }
  </script>

总结

以上所述是小编给大家介绍的django ajax发送post请求的两种方法,希望对大家有所帮助!

相关文章

python 将字符串转换成字典dict的各种方式总结

1)利用eval可以将字典格式的字符串与字典户转 》》》mstr = '{"name":"yct","age":10}' 转换为可以用的字典: 》》》eval(mstr), type(...

如何利用Boost.Python实现Python C/C++混合编程详解

前言 学习中如果碰到问题,参考官网例子: D:\boost_1_61_0\libs\python\test 参考:Boost.Python 中英文文档。 利用Boost.Python...

使用python搭建Django应用程序步骤及版本冲突问题解决

使用python搭建Django应用程序步骤及版本冲突问题解决

首先你要确保你机器上面安装了python,其次,你还要确保你上面安装了Django。接下来,才能进入到搭建第一个Django应用程序很简单的操作,即在windows终端输入代码:复制代码...

Python基于pygame模块播放MP3的方法示例

本文实例讲述了Python基于pygame模块播放MP3的方法。分享给大家供大家参考,具体如下: 安装pygame(可参考:安装Python和pygame及相应的环境变量配置) pip安...

用Pycharm实现鼠标滚轮控制字体大小的方法

用Pycharm实现鼠标滚轮控制字体大小的方法

一、pycharm字体放大的设置 File —> setting —> Keymap —>在搜寻框中输入:increase —> Increase Font Si...