2017-04-23 31 views
0

我有興趣從JSON格式的views.py中獲取插入操作的結果。我想,我得到的結果是好的。我的觀點如下所示:從jQuery中的django循環播放JSONResponse()結果

added={} 
if request.method=='POST': 
     #Post method initiated. 

     try: 
      for id in allergies: 
        allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user) 
       allergy.save() 
       added[allergy.id]=id 
     except BaseException as e: 
      pass 

return JsonResponse(added,safe=False) 

從JQUERY傳遞的記錄已成功添加到數據庫。我現在想要得到的是以{12:1,13:2}形式出現的JSON結果。

我firebag顯示響應爲:

12:1 
    13:2 

我不知道這是否一個有效的JSON或沒有。如果我列出(添加),它會給出:

0: 12 
    1: 13 

我不想要。我現在遇到的問題我想通過返回的項目,但我得到不正確的結果。我基本上想得到12:1,13:2。

  $.ajax({ 
      type: "POST", 
      url: "/patient/addallergy/", 
      data: postForm, 
      dataType : "json", 
      cache: "false", 
      success: function (result) { 

        alert(result.length); //gives undefined, rendering the below line meaningless 

        if (result.length>0){ 


         $.each(result,function(key,value){ 
          alert(key); 
          alert(value); 

          }); 

        } 


      }, 
      fail: function (result){ 

      } 


     }); 
+0

* 「不知道這是否是有效的JSON」 * ......有無數的JSON驗證在線 – charlietfl

+0

THX Charlietlf ... –

回答

1

改變你的意見這樣。

added_list=[] 
    if request.method=='POST': 
      #Post method initiated. 

      try: 
       for id in allergies: 
        added ={}     allergy=PatientAllergy(patient=patient,allergy_id=id,addedby=request.user) 
        allergy.save() 
        added[allergy.id]=id 
        added_list.append(added) 
      except BaseException as e: 
       pass 

    return JsonResponse(added_list,safe=False) 

和jQuery的

$.ajax({ 
     type: "POST", 
     url: "/patient/addallergy/", 
     data: postForm, 
     dataType : "json", 
     cache: "false", 
     success: function (result) { 

       alert(result.length); //gives undefined, rendering the below line meaningless 

       if (result.length>0){ 

        alert(JSON.stringify(result)) 
        $.each(result,function(index,value){ 
         console.log(value); 



         }); 

        result.forEach(function (eachObj){ 
         for (var key in eachObj) { 
            alert(key); 
          alert(eachObj[key]) 
          } 
         }); 

       } 


     }, 
     fail: function (result){ 

     } 


    }); 
+0

感謝@Thameem。完美的作品。 –