2017-04-23 9 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結果です。私は有効なJSONこの場合かどうかを確認していない

12:1 
    13:2 

:として

私firebagは応答を示しています。リストに追加すると、代わりに次のようになります。

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がオンラインにあります。完璧に動作します。 –