AJAX未传递硬编码数据

时间:2020-09-27 13:08:14

标签: javascript python json django ajax

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);
      }
    });
  });

我遇到以下错误:

enter image description here

因此我们知道由于弹出窗口,它正在进入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"})

2 个答案:

答案 0 :(得分:1)

我认为在您发送contentType中的json时,表单无法读取数据。只需删除该行即可。另外,您必须添加csrf标头才能发布请求。所以:

$.ajax({
      url: "/weather/",
      type: "POST",
      data: {
        "csrfmiddlewaretoken": $('[name=csrfmiddlewaretoken]').val(),
        "type_of_person": "1",
        "exercise": "2",
        "unit": "3",
        "zip_postal": "4"
      },
      dataType: "json",
      // contentType: "json", remove this
      success: function (data){
        alert("success");
      },
      error: function(xhr,errmsg,err) {
        alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
      }
    });

答案 1 :(得分:0)

好吧,如果您从服务器收到400状态代码,则调用success没有任何意义。

您的数据在前端有效并进入服务器,但未通过后端验证(或后端无法正确接受数据),因此将返回400错误请求。

在进行jQuery AJAX调用时,任何介于200-299之间且不同于304的错误代码都被视为错误。