2015-06-29 29 views
0

所以我正在學習jQuery,並且我創建了一個觸發器事件,當JSON數據被檢索時執行。我想要獲取所有的對象,但無法這樣做。我認爲這是由於如何檢索JSON對象。jQuery觸發器 - 返回只有一個對象,而不是所有JSON取回的對象

這是我正在使用的代碼。

<script> 

$.getJSON('http://jsonplaceholder.typicode.com/users', function(results){ 
    console.log(results) // prints the correct value. All the objects 
    $(document).trigger('jph/photos', results); 
}); 

$(document).on('jph/photos', function(e, results){ 
    console.log(results) // returns a single object?? 
    $('ul.tweets').html(
     $.map(results, function(obj, index){ 
      return '<li>'+obj.name+'</li>'; 
     }) 
    ); 
}); 
</script> 

回答

2

我認爲這個問題是,如果它是一個數組如果傳遞數組作爲第二個參數,則陣列中的每個對象被作爲一個單獨的參數給回調傳遞意味着額外參數值平坦化。

即,如果您傳遞一個包含3個項目的數組,則回調將總共接收4個參數,如function(event, item1, item2, item3){}而不是function(event, arrayof3items){}

一種解決方法是用另一個數組來包裝你的數組,這樣當封裝陣列是扁平的,將得到原始陣列,這將作爲參數傳遞給回調像

$.getJSON('http://jsonplaceholder.typicode.com/users', function (results) { 
    console.log(results) // prints the correct value. All the objects 
    $(document).trigger('jph/photos', [results]); 
}); 
+0

http://jsfiddle.net/arunpjohny/053ctyt5/ –

+0

你是什麼意思扁平? – Uma

2

嘗試傳遞設定參數爲.trigger作爲對象的陣列中,在事件處理程序利用Array.prototype.slice

var data = [{ 
 
    "name": 123 
 
}, { 
 
    "name": 456 
 
}]; 
 

 
$(document).on("jph/photos", function(e) { 
 
    // slice arguments starting at index 1 
 
    var results = Array.prototype.slice.call(arguments, 1); 
 
    $("ul.tweets").html(
 
    $.map(results, function(obj, index) { 
 
     return '<li>' + obj.name + '</li>'; 
 
    }) 
 
); 
 
}); 
 

 
$(document).trigger("jph/photos", data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
 
</script> 
 
<ul class="tweets"></ul>

+0

我不知道爲什麼會發生這種情況,我嘗試了另一個json數據,它運行良好,並且有一些我正面臨着這個問題。 – Uma

+0

不確定解釋_「我不確定爲什麼會發生這種情況,我嘗試了另一個json數據,它運行正常,並且有一些我正面臨此問題。」_正確嗎?問題是否解決? – guest271314

+0

是的,事實上這兩個答案都起作用。雖然我有點困惑,但在某些情況下,我不需要使用原型並獲得所有對象,但在這些情況下,我必須使用原型。我不確定爲什麼會發生這種情況。 – Uma

相關問題