2017-04-11 223 views
0

我正在進行AJAX調用,並希望它返回對象字典。無論我如何嘗試返回數據,它都會引發異常。據我所知,這隻能是因爲響應數據不是JSON格式。使用Django從AJAX調用返回字典

任何幫助將非常感激

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" 
      ) 
+0

什麼是例外? –

+4

擺脫try..except塊。你會知道錯誤是什麼。另外,它是一個bd編程實踐,可以在代碼爲 – karthikr

回答

0

是的,謝謝你的幫助!我需要使用序列化程序,因爲我正在創建一個對象字典。由於對象沒有正確序列化,因此json_response的格式不正確,並且因此引發了錯誤。

+0

的大塊上捕獲泛型異常好極了!如果我的回答對你有幫助,你可以將其標記爲正確的答案,並給它一個投票。 –