【问题标题】:How to catch Django's response of an Ajax call如何捕捉 Django 对 Ajax 调用的响应
【发布时间】:2020-06-29 16:45:43
【问题描述】:

我正在使用 Ajax 将表单数据转换为 JSON 并将其发送到我的 Django 视图。成功处理后,我将返回一个模板响应,其中包含一些我无法在我的 HTML 中引用的上下文数据。我坚持让这个工作。任何帮助将非常感激。下面是我的 HTML 代码和我的 Django 视图。

查看:

class CustomerAttributeView(View):
    """
    Saves the attribute details for a user.
    Updates if already present
    """
    page = 'customer_attributes.html'

    def get(self, request):
        return render(request, self.page)

    def post(self, request):

        try:
            user = User.objects.get(id=request.session['user_id'])
            data = json.loads(request.POST.get('data'))

            attribute_ids_mapped_to_customer = CustomerAttributeMapping.objects.\
                filter(consuming_app_id=user.consuming_app_id).values_list('id', flat=True)

            #If no attributes mapped to the user then create and return
            if not attribute_ids_mapped_to_customer:
                insert_or_update_customer_attributes(user, data)
                context_data = {
                    'success_msg': 'Attribute details saved successfully'
                }
                return TemplateResponse(request, self.page, context=context_data)
        except Exception as e:
            logging.error("Error: " + str(e))
            context_data = {
                'error_msg': 'Error in saving customer attributes',
                'status_code': 400
            }
            return TemplateResponse(request, self.page, context=context_data)

AJAX:

$.ajax({
            url : "customer_attribute/", // the endpoint
            type : "POST", // http method
            data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
    });

网址:

urlpatterns = [
    url(r'^customer_attribute/',csrf_exempt(CustomerAttributeView.as_view())),
]

我试图引用从视图返回的上下文数据的 HTML 代码:

<span class="success-msg" id="success_msg">{% if success_msg %}{{ success_msg }}{% else %} {{""}} {% endif %}</span>
<span class="error" id="error_msg">{% if error_msg %}{{ error_msg }}{% else %} {{""}} {% endif %}</span>

我的 HTML 中既没有看到 success_msg 也没有看到 error_msg。我在这里做错了什么吗?

【问题讨论】:

  • 模板由 Django 在发送到浏览器之前呈现。执行 javascript 后,您无法使用 django 模板执行任何操作。

标签: javascript python django ajax


【解决方案1】:

您正在发起一个 Ajax 请求,但您从未收到它的响应。您应该在 JavaScript 代码中定义响应处理程序。我假设您使用jQuery's $.ajax()。以下代码会将响应原样注入到 ID 为 reponse 的容器中。

const xhr = $.ajax({
    url : "customer_attribute/", // the endpoint
    type : "POST", // http method
    data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
});

xhr.done(function (response) {
    $('#response').html(response)
});

但我猜 customer_attributes.html 是整个页面的模板。可能您不想再次被包含在内。您可能希望创建一个单独的 HTML 模板,该模板仅呈现您想要在成功时返回的 sn-p。

如果您想要一种更复杂的方式来处理响应数据,您可能希望您的 Django 视图而不是 HTML 输出,而是返回一个 JSON 格式的数据,您可以在客户端更好地处理该数据 (see Django's JsonResponse)。

总的来说,我建议使用您的网络浏览器的开发工具箱来调试此类问题,它应该有一个网络检查器工具。当您执行 Ajax 请求时,您应该看到一个带有所有请求数据的请求进入您的后端——您还应该在那里观察后端给您的响应。这样您就可以首先确认后端是否按照您的预期给出了响应。

【讨论】:

    【解决方案2】:

    您没有指定成功回调

    $.ajax({
                url : "customer_attribute/", // the endpoint
                type : "POST", // http method
                data : {data:JSON.stringify(attribute_data)}, // data sent with the post request
                success: (response) => {// do logic 
    
       }
        });
    

    ref

    【讨论】:

      猜你喜欢
      • 2017-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      相关资源
      最近更新 更多