2016-01-21 29 views
0

我是jquery和javascript的新手,我用ajax上傳我的圖片並希望獲取圖片url,我試過了,我一直都在收到錯誤。任何人都可以幫助我解決這個問題?謝謝!解析json數組得到一定的索引

錯誤我收到:

Uncaught TypeError: Cannot read property 'length' of undefined 

這裏是調用URL後的結果:

{"status_code":200,"status_txt":"OK","data":{"img_name":"nfFWV.jpg","img_url":"http:\/\/sl.uploads.im\/nfFWV.jpg","img_view":"http:\/\/uploads.im\/nfFWV.jpg","img_width":"3840","img_height":"2160","img_attr":"width=\"3840\" height=\"2160\"","img_size":"3.1 MB","img_bytes":3226508,"thumb_url":"http:\/\/sl.uploads.im\/t\/nfFWV.jpg","thumb_width":360,"thumb_height":203,"source":"base64 image string","resized":"0","delete_key":"338aa524f1654056"}} 

這裏是我的代碼:

var imgfile = $('#receipt').get(0).files[0]; 
     $.ajax({ 
      type: 'POST', 
      url: 'http://uploads.im/api?upload='+imgfile, 
      dataType: 'json', 
      data:formData, 
      cache: false, 
      contentType: false, 
      processData: false, 
      success: function(data){ 
       var htmlStr = ''; 
    $.each(data, function(k, v){ 
     $.each(v.data, function(s, a){ 
     htmlStr += a.img_url + '<br />'; 
     }); 
    }); 
    alert(htmlStr); 
      } 

      }); 
+0

data.data.img_url似乎是正確的 – jilykate

+0

爲什麼你需要$。每?它簡單易懂的json.No需要$。每 –

回答

0

如果要訪問返回的JSON的個人財產,那麼你可以這樣做。

var imgObj = data.data // your response in success callback 
var imgName = imgObj.img_name; 
var imgUrl= imgObj.img_url; 

// in this way you can access rest of property 

無需任何類型的循環一樣$.each

+0

感謝!這樣可行 – MuthaFury

0

jQuery的每個未使用這條路。您可以使用控制檯輸出你的代碼:

the first each loop

你可以看到,你正試圖從數據的每一個項目獲得img_url。

你應該: the right way