【问题标题】:Return dictionary from AJAX call using Django使用 Django 从 AJAX 调用返回字典
【发布时间】:2017-04-11 00:28:36
【问题描述】:

我正在进行 AJAX 调用并希望它返回一个对象字典。无论我如何尝试返回数据,它都会引发异常。据我所知,只能是因为响应数据不是 JSON 格式。

任何帮助将不胜感激

def populateSources(request):
    if request.is_ajax():
        try:
            org = Organization.objects.get(pk=int(request.GET.get('org_id')))
            std_source_columns = StandardizedSourceColumn.objects.all()
            std_sources = StandardizedSource.objects.all()

            # Standardized Tables API Client
            std_tables_api_client = standardizedtablescli.ApiClient()
            std_tables_api_client.host = os.environ.get('STANDARDIZED_ENDPOINT')
            std_tables_api = standardizedtablescli.StandardizedtablesApi(std_tables_api_client)

            org_std_sources = std_tables_api.get_standardized_tables_by_id(org.id)
            ready_tables = std_tables_api.get_ready_raw_tables(org.id)

            ready_table_mapping = dict()
            ready_table_names = []

            for table in ready_tables:
                ready_table_names.append(table)


            for key, value in org_std_sources.iteritems():
                curr_source = StandardizedSource.objects.filter(name=key)
                if len(value['standard_mappings']) == 0:
                    if key in ready_table_names:
                        ready_table_mapping[curr_source] = False
                else:
                    ready_table_mapping[curr_source] = True

            json_response = {}
            json_response['result'] = ready_table_mapping
            return HttpResponse(
                json.dumps(json_response),
                content_type="application/json"
            )
        except:
            return HttpResponse(
                json.dumps("error"),
                content_type="application/json"
            )

【问题讨论】:

  • 有什么例外?
  • 去掉 try..except 块。你会知道错误是什么。此外,在如此大的代码块上捕获通用异常是一种 bd 编程实践

标签: jquery python json ajax django


【解决方案1】:

您可以改用序列化,参考 django 文档https://docs.djangoproject.com/en/1.10/topics/serialization/

【讨论】:

    【解决方案2】:

    是的,谢谢你的帮助!我需要使用序列化程序,因为我正在创建一个对象字典。由于对象未正确序列化,因此 json_response 格式不正确并因此引发错误。

    【讨论】:

    • 太棒了!如果我的回答对您有帮助,您可以将其标记为正确答案并投赞成票。
    猜你喜欢
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2011-02-20
    • 1970-01-01
    • 2019-06-03
    • 2019-01-09
    相关资源
    最近更新 更多