简体   繁体   English

AJAX 不传递硬编码数据

[英]AJAX is not passing hard-coded data

In index.js I have: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);
      }
    });
  });

I'm getting the following error:我收到以下错误:

在此处输入图片说明

So we know it's going into the error function of the AJAX call because of the popup.所以我们知道它会因为弹出窗口进入 AJAX 调用的错误函数。 But why?但为什么?

I specifically hard-coded the JSON values to pass.我专门硬编码了要传递的 JSON 值。

The view that processes the AJAX data:处理 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)

Things I've tried, but to no avail:我尝试过但无济于事的事情:

  • data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"})

I think the form could not read data as you are sending contentType of json .我认为表单无法读取数据,因为您正在发送json contentType Just removing that line should work.只需删除该行即可。 Also, you have to add csrf header to post request.此外,您必须添加csrf标头来发布请求。 So:所以:

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

Well, it doesn't make sense to call success if you're receiving a 400 status code from the server.好吧,如果您从服务器收到 400 状态代码,则调用success是没有意义的。

Your data is valid in frontend and goes to the server, but it does not pass backend validations (or the backend fails to accept it properly) and therefore it returns you 400 Bad Request.您的数据在前端有效并进入服务器,但它没有通过后端验证(或后端无法正确接受它),因此它向您返回 400 Bad Request。

Any error code that is between 200-299 and different than 304 is considered an error when making an jQuery AJAX call.在进行 jQuery AJAX 调用时,任何介于 200-299 和 304 之间的错误代码都被视为错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM