问题描述
现在发生的是,当我单击提交(“ Go!”)时,Django清除了整个页面,然后在空白页面上打印正确的JSON响应 results_matrix 。 警报(“成功”)未出现或警报(“错误”)。 我不知道为什么post函数会这样做,因为我没有返回任何东西的渲染。
点击“开始!”之前:
点击“开始!”在Chrome浏览器中:
ajax调用返回的是原始json文件以下载(Chrome会在浏览器中自动显示该文件),而不是进入ajax成功函数。
预期的行为:页面保持不变,但弹出窗口显示“成功”。
在 index.js 中:
$(document).ready(function() {
var csrftoken = Cookies.get("csrftoken");
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr,settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken",csrftoken);
}
}
});
$(document).on("submit","#weather_form",function(event){
// //Prevent default django post behaviour for a form submission.
event.preventDefault();
$.ajax({
url: "/weather/",type: "POST",data: {type_of_person: $("#id_type_of_person").val(),exercise: $("#id_exercise").val(),unit: $("#id_unit").val(),zip_postal: $("#id_zip_postal").val()},dataType: "json",contentType: "application/json",success: function (data){
alert("success");
},error: function(xhr,errmsg,err) {
alert("error");
console.log(errmsg + "\n" + xhr.status + ": " + xhr.responseText)
}
});
return false;
});
});
在 index.html 中:
<form action="/weather/" method="post" autocomplete="off" id="weather_form">
{% csrf_token %}
{{ form.non_field_errors }}
{{ error }}
<ul>
<li class="center_text">
<h3>Best Time to Go Out</h3>
</li>
<li>
<label>{{ form.type_of_person.label }}: </label>
{{ form.type_of_person }}
{{ form.type_of_person.errors }}
</li>
<li>
<label>{{ form.exercise.label }}: </label>
{{ form.exercise }}
{{ form.exercise.errors }}
</li>
<li>
<label>{{ form.unit.label }}: </label>
{{ form.unit }}
{{ form.unit.errors }}
</li>
<li>
<label>{{ form.zip_postal.label }}: </label>
{{ form.zip_postal }}
{{ form.zip_postal.errors }}
</li>
<li>
<input id="go" type="submit" value="Go!">
</li>
</ul>
</form>
在 views.py 中:
class weather(base.TemplateView):
...
@staticmethod
def post(request,*args,**kwargs):
...
if form.is_valid():
...
return http.JsonResponse({"results_matrix": results_matrix.tolist()},status=200)
else:
return http.JsonResponse({"error": form.errors},status=400)
编辑#1:
编辑#2:
我尝试过的其他尝试,但无济于事:
- 将
async: false
添加到ajax调用中。 - 将ajax调用定向为由另一个视图而不是当前视图处理。
编辑#3:
此网络应用程序的依赖性:
-
jquery-ui-1.12.1 / jquery-ui.min.css
-
jquery-ui-1.12.1 / jquery-ui.structure.min.css
-
jquery-ui-1.12.1 / jquery-ui.theme.min.css
-
jquery-3.5.1.min.js
-
jquery-ui-1.12.1 / jquery-ui.min.js
-
index.js
-
index.css
-
Django 3.1
解决方法
只需从操作属性中删除天气URL。因为在调用ajax之前先调用天气类。
<form action="" method="post" autocomplete="off" id="weather_form">
{% csrf_token %}
{{ form.non_field_errors }}
{{ error }}
<ul>
<li class="center_text">
<h3>Best Time to Go Out</h3>
</li>
<li>
<label>{{ form.type_of_person.label }}: </label>
{{ form.type_of_person }}
{{ form.type_of_person.errors }}
</li>
<li>
<label>{{ form.exercise.label }}: </label>
{{ form.exercise }}
{{ form.exercise.errors }}
</li>
<li>
<label>{{ form.unit.label }}: </label>
{{ form.unit }}
{{ form.unit.errors }}
</li>
<li>
<label>{{ form.zip_postal.label }}: </label>
{{ form.zip_postal }}
{{ form.zip_postal.errors }}
</li>
<li>
<input id="go" type="submit" value="Go!">
</li>
</ul>
</form>
,
最后找到了问题的根源。耶稣基督。
在我的index.js
中,我有:
var csrftoken = Cookies.get("csrftoken");
但我从未导入JavaScript Cookie库。
我最终没有使用该库,并通过将以下行替换为以下内容来解决了这个问题:
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0,name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');