【问题标题】:Where can I put .filter method in my AJAX request with jQuery我可以在哪里使用 jQuery 在我的 AJAX 请求中放置 .filter 方法
【发布时间】:2017-06-02 07:11:20
【问题描述】:

我正在使用“GET”请求从这个API检索信息

“GET”请求很好,但是有些对象没有图像缩略图作为我的来源,我想过滤掉它们,但似乎不知道该方法放在哪里,这是我的代码

$(document).ready(function(){
  $('button').on('click', function(event){
    event.preventDefault();
    $('#result').empty();
    var userInput = $('input').val()
      $.ajax({
        method:"GET",
        url:"https://www.reddit.com/r/" + userInput + ".json?jsonp",
        success:success
      })
  })
  function success(response){
    var result ="";
    var zero = "0"
    $.each(response, function(index, value){
        var list = response.data.children
        $.each(list.slice(1).slice(0, 12), function(index,value){
            var thumbnail = value.data.thumbnail
            result += "<li>" + "<img src='" + thumbnail + "'/>"
            $('#result').html(result)
        })
    })
  }
})

另外,如果您知道如何构建我的代码,那么我只需要创建一个 $.each 循环,那也会有所帮助!

非常感谢,

詹姆斯

【问题讨论】:

  • return thumbnail !== "" &amp;&amp; thumbnail !== null 条件下使用jquery.filter 在您的success
  • 请在下面链接我认为这将解决您的问题。 stackoverflow.com/questions/4245231/…

标签: javascript jquery ajax


【解决方案1】:

使用filter过滤掉列表中带有虚假缩略图的项目(null或未定义等)

var list = response.data.children.filter(function(item) {
   return item.data.thumbnail;
});

$.each(list, function(index,value){
   var thumbnail = value.data.thumbnail;
   $('#result').html(result)
})

【讨论】:

  • 它似乎没有引起任何错误,一些缩略图的值是'self',它不是一个 URL,所以我不能使用它。我正在尝试使用 if 语句,但不知道该去哪里。 if(value.data.thumbnail == self){ ** 跳到下一个** }
  • 您可以将其添加到过滤条件中。 return item.data.thumbnail &amp;&amp; item.data.thumbnail !== 'self';
【解决方案2】:

Promises 将帮助您拥有更结构化的代码, Array.prototype.reduce 将帮助您避免不必要的迭代。

function loadRedditData(keyword) {
  return jQuery
    .get(`https:\/\/www.reddit.com\/r\/${keyword}.json`, {jsonp: ''})
    .then(res => res.data.children.slice(1, 12))
    .then(data => (
      data.reduce((html, item) => {
        let card = `<h5>${item.data.name}</h5>`;
        
        if(item.data.thumbnail) {
          card = `<img src="${item.data.thumbnail}" />`;
        }
        
        return html.concat(`<div class="card">${card}</div>`);
      }, '')
    ))
    .then(html => jQuery('#result').html(html))
  ;
}

$(document).ready(function() {
  $('button').click(function() {
    return loadRedditData(jQuery('input').val() || 'Ecmascript 6');
  });

})
#result {
  border: 1px solid cyan;
  margin: 5px;
  padding: 5px;
  min-height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Load Your Data</button>
<input value="javascript" />
<hr />
<section id="result"></section>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多