微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax 把get请求改为post请求django

以下代码可以正常运行。(index.js文件

setInterval(function () {
       console.log( "kaishi" + timeText())
  $.ajax(
    {
        type:'get',  // 不指定认就是get,都是小写
        success:function (response) {
        console.log(response)
            $('#picture').attr('src', response.imgPath) 	 //修改<img>标签的src值
            $('#number').text(response.result)		//修改id="number"标签内容
            }
        }
  )
},10000)	//10s

​ 我希望与页面加载的同时,此代码就开始执行,并且每隔10s执行一次。

​ 为了和首次打开页面区分,我把ajax请求的类型改为post,其他不变

type:'post'

会报如下错误(ajax发送的请求为我的首页):

Forbidden (CSRF token missing.): /index/

解决办法:

  • 第一步 index.html : 引用query.cookie.js插件(建议将此文件下载到本地,不然只能在联网下使用,可以确定此方法可行后再下载)
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  • 第二步 index.js : 在success函数添加请求头 headers: {“X-CSrftoken”: $.cookie(‘csrftoken’)}
setInterval(function () {
      console.log( "kaishi" + timeText())
 $.ajax(
   {
       type:'post',  // 不指定认就是get,都是小写
       //以下是添加代码
       headers: {"X-CSrftoken": $.cookie('csrftoken')},
       //以上是添加代码
       success:function (response) {
       console.log(response)
           $('#picture').attr('src', response.imgPath) 	 //修改<img>标签的src值
           $('#number').text(response.result)		//修改id="number"标签内容
           }
       }
 )
},10000)	//10s

过程中遇到的报错:

  • 第一种 : 在浏览器查看控制台报错:

    在这里插入图片描述


    原因 : cookie的问题,需要在index.html文件中引用query.cookie.js插件
<script src="https://cdn.staticfile.org/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
  • 第二种 : 终端报错:
Forbidden (CSRF token missing.): /index/

原因:没有加入这句代码

headers: {"X-CSrftoken": $.cookie('csrftoken')},

原文地址:https://www.jb51.cc/wenti/3282982.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐