2017-08-30 48 views
0

這就是我目前正在做的事情。我試着將我的json中的值推入鏈接數組中,但輸入數組後,值變爲undefined。什麼是移動數據並使其仍然可用的更好方法?從使用此代碼從我的JSON對象添加到我的列表數組中

var links = []; 
$.ajax({ 
    url: 'data.json', 
    dataType: 'json', 
    type: 'get', 
    cache: false, 
    success: function(data) { 
    $(data.emails).each(function(index, value) { 
     links.push(value); 
    }); 
    } 
}); 

//data.json contains: 
{ 
    "emails": [{ 
    "source": "[email protected]", 
    "target": "[email protected]" 
    }] 
} 

結果是相同的。值輸入數組,但是當您通過鏈接訪問它們。(值的名稱)返回「未定義」

$.each(data.emails, function(index, value) { 
     links.push(value); 
     console.log(links); 
     return value; 
    }); 

Result

+0

裏面是什麼 「數據」? – Sletheren

+0

真正的問題是你在哪裏返回,你在哪裏檢查'links'數組,爲什麼該數組有一個'target'屬性? – adeneo

+0

你在哪裏檢查'links'數組?請注意,AJAX請求是異步的。 –

回答

0

嘗試這個

<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>   
<script type="text/javascript"> 
//alert("data"); 
var links = []; 
    $.ajax({ 
     url: 'test1.php', 
     type: 'post', 
     dataType: 'json', 
     data: { 

     } 
     }).done(function(data) { 
     $.each(data.emails, function(index, value) { 
     links.push(value); 
     console.log(links); 
     return value; 
     }); 
    }); 

    function getVal(){ 
     console.log(links[0].target); 
    } 
</script> 
<button onclick="getVal()">Get target</button> 
+0

主要問題是該調用是異步的,我不知道這一點。 –

0

我覺得你的成功回調代碼是錯誤的,

正確的方式循環data.emails是,

success: function(data) { 
     $.each(data.emails, function(index, value) { // <--- change this 
      links.push(value); 
      console.log(links); //<--- updated 
      return value; 
     }); 
    } 
+0

你是正確的,因爲在這種情況下使用$ .each更正確,但是,這不是導致問題的原因。 $()可以從任何類似數組的結構創建一個集合,並且.each將迭代它。 –

0

你的AK調用console.log這不存在。修改您的代碼來調用並打印出數組,而不是隨機屬性。

var links = []; 
    $.ajax({ 
    url: 'data.json', 
    dataType: 'json', 
    type: 'get', 
    cache: false, 
    success: function(data) { 
     $(data.emails).each(function(index, value) { 
      links.push(value); 
      console.log(links); 
      return value; 
     }); 
    } 
}); 
相關問題