如何将Django项目中的$.ajax()代码转换为fetch()并解决CSRF校验报错
修复后可正常运行的代码
function myidLikeCom(params) { // 构造表单格式参数,匹配原$.ajax的默认传参格式 let formData = new FormData(); formData.append('postid', params); formData.append('csrfmiddlewaretoken', $('input[name=csrfmiddlewaretoken]').val()); formData.append('action', 'post'); fetch('{% url "boards:likeComment" %}', { method: 'POST', body: formData // 用FormData时浏览器会自动补充正确的Content-Type头,无需手动设置 }) .then(response => response.json()) .then(json => { // 对应原代码success逻辑 document.querySelector(`#myidLikeCom${params}`).innerText = json['result']; }) .catch((err) => { // 对应原代码error逻辑 }) }
核心修改点
- 替换直接传递JS对象的写法,改用
FormData封装所有请求参数:jQuery的$.ajax会自动将data字段的普通对象转为application/x-www-form-urlencoded格式的请求体,fetch没有这个自动转换逻辑,直接传JS对象会导致Django无法正常解析参数,也就读不到csrfmiddlewaretoken的值触发校验失败 - 补全了原有请求中必填的
action: 'post'参数 - 补充了响应解析、成功/错误回调逻辑,和原有
$.ajax的功能完全一致
可选JSON传参方案
如果你的后端接口适配了JSON格式请求,可以用这个写法,直接把CSRF Token放在请求头中:
function myidLikeCom(params) { fetch('{% url "boards:likeComment" %}', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() }, body: JSON.stringify({ postid: params, action: 'post' }), }) .then(response => response.json()) .then(json => { document.querySelector(`#myidLikeCom${params}`).innerText = json['result']; }) }
内容的提问来源于stack exchange,提问作者xh9tlf8d82
相关产品推荐
相关产品推荐

