Django通过AJAX POST传值时报Uncaught RangeError栈溢出如何解决
问题修复方案
1. 栈溢出报错的核心原因
你在AJAX的data字段里传递的textOfFile是通过document.getElementById('fileinput')拿到的DOM节点对象,不是你读取到的文件文本。jQuery在序列化这个DOM对象的时候会递归遍历它的所有属性,DOM对象属性极多还存在循环引用,直接触发栈溢出。
修复方法:你已经把文件读取结果放到了id为textarea的元素里,直接传递这个值即可。
2. AJAX配置的其他错误
dataType参数写错,jQuery合法取值为xml、json、script、html、text,不存在String,改为dataType: "text"- AJAX配置对象最后多了多余逗号,把
},);}改为});} - 错误回调参数名写错,jQuery的AJAX失败回调是
error不是failure - 缺少Django POST请求必需的CSRF校验参数,需要补充CSRFToken到请求头
3. urls.py的路由错误
你定义的name='textFromInputFile'对应的路由路径是home.html,但AJAX里写的请求路径是/textFromInputFile,完全匹配不上。同时home.html路径同时绑定了views.home和views.textFromInputFile两个视图,前面的会覆盖后面的,根本访问不到上传接口。
修复方法,把urls.py对应行修改为:
path('textFromInputFile', views.textFromInputFile, name='textFromInputFile'),
4. views.py的语法错误
视图函数代码缩进错误,if request.method == 'POST'及后续代码都要缩进一层放在函数内部:
def textFromInputFile(request): if request.method == 'POST': if 'textOfFile' in request.POST: textOfFile = request.POST['textOfFile'] # 你的业务逻辑 return HttpResponse('success') else: return HttpResponse('failed!!')
修复后完整JS代码参考
<script> // 模板中需要先渲染{% csrf_token %},才能获取到csrf值 const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; const textOfFileInput = document.getElementById('fileinput'); textOfFileInput.addEventListener('change', function(){ const fr = new FileReader(); fr.onload = function(){ document.getElementById("textarea").value = fr.result; }; fr.readAsText(this.files[0]); }); function getText(){ $.ajax({ type: "POST", url: "{% url 'textFromInputFile' %}", // 用模板标签生成url,避免硬写错误 headers: {'X-CSRFToken': csrftoken}, data: {"textOfFile": document.getElementById("textarea").value}, dataType: "text", success: function(data){ alert("ok") }, error: function(){ alert("failed") } }); } $('button').click(function(){ getText(); }); </script>
内容的提问来源于stack exchange,提问作者Abdul Qader
相关产品推荐
相关产品推荐

