首页 > 解决方案 > JsonResponse 和 HTTPResponse 有什么区别?

问题描述

我正在关注一个教程,这个人使用了这两行代码。我试图了解 JsonResponse 和 HttpResponse 之间的区别。

JsonResponse 和 HttpResponse 都会导致用户收到弹出消息 ( $.alert({)。

当这两种情况下的输出都是一个$.alert({时,我有点困惑为什么你在一个实例中需要一个 JsonResponse 而在另一个实例中需要一个 HttpResponse 。

  if request.is_ajax():
     return JsonResponse({"message": "Thank you for your submission"})
         
    
  if request.is_ajax():
     return HttpResponse(errors, status=400, content_type='application/json')

视图.py

if contact_form.is_valid():
            print(contact_form.cleaned_data)

    if request.is_ajax():
        return JsonResponse({"message": "Thank you for your submission"})
     
if contact_form.errors:
    print("there are errors")
    errors = contact_form.errors.as_json()
    if request.is_ajax():
        return HttpResponse(errors, status=400, content_type='application/json')

电子商务.js

  displaySubmitting(contactFormSubmitBtn, "", true)
  $.ajax({
    method: contactFormMethod,
    url:  contactFormEndpoint,
    data: contactFormData,

    success: function(data){
      contactForm[0].reset()
      $.alert({
        title: "Success!",
        content: data.message,
        theme: "modern",
      })
      setTimeout(function(){
        displaySubmitting(contactFormSubmitBtn, contactFormSubmitBtnTxt, false)
      }, 500)
    },
    error: function(error){
      console.log(error.responseJSON)
      var jsonData = error.responseJSON
      var msg = ""

      $.each(jsonData, function(key, value){ // key, value  array index / object
        msg += key + ": " + value[0].message + "<br/>"
      })

      $.alert({
        title: "Oops!",
        content: msg,
        theme: "modern",
      })

这是联系表格

在此处输入图像描述

这是您输入正确数据后的联系表格

在此处输入图像描述

这是有错误的联系表单(在这种情况下,错误是用户没有输入 Gmail 地址)。

在此处输入图像描述

标签: javascriptpythonjsondjangohttp

解决方案


推荐阅读