2017-01-24 151 views
0

我有一個問題遍歷從上傳的文件數據返回的對象,但它似乎有可能正在返回的對象結構阻止我從響應中的每個對象捕獲特定的屬性或我誤解了我應該如何訪問這個對象。當我登錄data.length時,我得到了995,我假設它是對象響應中的字符數。當我登錄data[prop]它記錄每個單獨的字符。JavaScript對象結構問題

這是我返回的文件對象的數據:

[ 
    { 
    "fieldname": "fileUpload", 
    "originalname": "Screen Shot 2017-01-08 at 12.23.39 PM.png", 
    "encoding": "7bit", 
    "mimetype": "image/png", 
    "size": 39881, 
    "bucket": "test", 
    "key": "1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png", 
    "acl": "public-read", 
    "contentType": "image/png", 
    "contentDisposition": null, 
    "storageClass": "STANDARD", 
    "metadata": null, 
    "location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png", 
    "etag": "\"sfasgltg702o\"" 
    }, 
    { 
    "fieldname": "fileUpload", 
    "originalname": "Screen Shot 2017-01-08 at 12.21.04 PM.png", 
    "encoding": "7bit", 
    "mimetype": "image/png", 
    "size": 58386, 
    "bucket": "test", 
    "key": "1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png", 
    "acl": "public-read", 
    "contentType": "image/png", 
    "contentDisposition": null, 
    "storageClass": "STANDARD", 
    "metadata": null, 
    "location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png", 
    "etag": "\"151353j53j51u5j135ju\"" 
    } 
] 

jQuery的AJAX POST請求上傳文件並返回對象data

$.ajax({ 
      url: '/app/sign', 
      type: 'POST', 
      data: formData, 
      processData: false, 
      contentType: false, 
      success: function(data){ 
       console.log('upload successful! ' + data); 

       console.log('Just the key ' + data.length); 
       for(var prop in data){ 
        console.log(data[prop]); 
       } 
      }, 
      error: function(error){ 
       console.log('error ' + JSON.stringify(error)); 
      } 
     }); 

回答

2

data是一個JSON字符串,你必須使用JSON.parse這樣分析它回到對象的數組:

success: function(data){ 
    var arr = JSON.parse(data); 

    // use arr as array 
    console.log(arr.length); 
    // arr[0] is the first object 
} 
1

這只是一個以JSON格式。您需要將JSON.parse轉換爲JS對象,或使用$.getJSON()

0

比方說,你要訪問的第一fieldname,您可以訪問它這樣data[0].fieldname 。第二個也是如此:data[1].fieldname。爲什麼?因爲你的數據是這樣解釋的:

0: {"fieldname": "fileUpload", ...}, 1: {"fieldname": "fileUpload", ...}