jQuery Trigger - 仅返回单个对象,而不是JSON提取的所有对象

时间:2015-06-29 04:31:18

标签: javascript jquery json

所以我正在学习jQuery,并且我创建了一个在检索JSON数据时执行的触发器事件。我希望获取所有对象,但我无法这样做。我认为这是由于如何检索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 个答案:

答案 0 :(得分:2)

我认为问题是如果它是一个数组意味着额外的params值被展平,这意味着如果你将一个数组作为第二个参数传递,那么数组中的每个对象都作为一个单独的参数传递给回调。

即,如果您传递包含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]);
});

答案 1 :(得分: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>