【发布时间】:2021-01-13 05:55:44
【问题描述】:
在index.js 我有:
$("#weather_form").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "/weather/",
type: "POST",
data: {type_of_person: "1",
exercise: "2",
unit: "3",
zip_postal: "4"},
dataType: "json",
contentType: "json",
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
});
我收到以下错误:
所以我们知道它会因为弹出窗口而进入 AJAX 调用的错误函数。但为什么呢?
我专门硬编码了要传递的 JSON 值。
处理 AJAX 数据的视图:
class weather(base.TemplateView):
template_name = "weather/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = forms.input_form()
return context
@staticmethod
def post(request, *args, **kwargs):
form = forms.input_form(request.POST)
if form.is_valid():
# process the data
type_of_person = form.cleaned_data["type_of_person"]
exercise = form.cleaned_data["exercise"]
unit = form.cleaned_data["unit"]
zip_postal = form.cleaned_data["zip_postal"]
results_matrix = interface.get_results_matrix(type_of_person, unit, exercise, zip_postal)
return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
else:
return http.JsonResponse({"error": form.errors}, status=400)
我尝试过的方法,但无济于事:
data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"})
【问题讨论】:
-
向我们展示您发送数据的视图
-
@BiploveLamichhane 完成!我更新了处理 AJAX 数据的视图。
标签: javascript python json django ajax