【问题标题】:AJAX is not passing hard-coded dataAJAX 不传递硬编码数据
【发布时间】: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


【解决方案1】:

我认为当您发送contentTypejson 时,表单无法读取数据。只需删除那条线就可以了。此外,您必须添加 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);
      }
    });

【讨论】:

  • 嘿,成功了! dataTypecontentType 有什么区别?
  • 嗯,contentType 是我们发送到服务器的数据,dataType 是服务器发送的数据类型或响应数据。请参阅here 了解更多详情。
【解决方案2】:

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

您的数据在前端有效并发送到服务器,但未通过后端验证(或后端无法正确接受),因此返回 400 Bad Request。

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

【讨论】:

    猜你喜欢
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多