json - 使用ajax POST将json数据从浏览器发送到Django视图后没有响应
问题描述
我正在使用 handsontable 在我的 Web 应用程序上模拟电子表格。我想将用户输入电子表格的 json 数据发送到我的数据库。
html按钮:
<button id="send_post" class="btn size-medium bg-green text-white shadow hover-moveup">Send Post Request</button>
JS:
document.getElementById("send_post").addEventListener("click", function(event) {
$.ajax({
url: 'http://127.0.0.1:8000/',
headers: { "X-CSRFToken": csrf_token },
type: "POST",
dataType: "json",
data: JSON.stringify(hot.getSourceData()),
statusCode: {
200: function (your_Response_Data) {
console.log(JSON.stringify(hot.getSourceData()))
},
// ... handle errors if required
404: function () {
}
},
complete: function (jqXHR, textStatus) {
}
});
})
视图.py
@login_required(login_url='/login/')
def index(request):
user_id = request.user
if request.is_ajax():
if request.method == "POST":
received_json_data = json.loads(request.body)
return HttpResponse(received_json_data, content_type="application/json")
终端:
[04/Apr/2019 01:19:23] "POST / HTTP/1.1" 302 0
我在视图中收到数据,但 Httpresponse 没有将数据返回给浏览器。
解决方案
通过在成功的 POST 请求时设置 location.href 来解决它
statusCode: {
200: function (your_Response_Data) {
console.log(JSON.stringify(hot.getSourceData()));
location.href = "/";
},
推荐阅读
- flutter - [Flutter]同款中英文高度与中文高度不一致
- python - 在python中查找邻居邻居的最有效方法
- apache-camel - 如何使用骆驼调用内容类型为 x-www-urlencoded 的 POST api
- delphi - 如何在 Delphi 中使用 Abbrevia AbZip 排除根目录的提取
- ios - 选择另一个 UITextView 时,UIScrollView 滚动到上一个 UITextView
- c++ - 我已经解决了 Hackerrank 上的平衡括号,我遇到了这个错误......有人可以帮我理解这个吗?
- json - 具有多个 JsonProperty Newtonsoft.Json 的 Json 序列化器
- javascript - 如何选择特定范围
- 2 id 之间的项目并在 Javascript / jQuery 中对它们进行排序
- python - 运行 GitHub 操作时找不到已安装的包
- java - 在 FTL 中读取多个属性文件