0

我无法摆脱 for 循环。

现在,循环在每个页面上执行一个 jQuery getJSON 调用。如果页面有数据,它会记录所有项目。如果页面没有数据,循环应该完全停止。

但是,每当我运行它时,它都会遍历所有 100 页。一旦点击没有数据的页面,它会记录“此页面没有内容”,但会继续运行 for 循环。(因此在我的控制台中以源源不断的“此页面没有内容”结束)

我究竟做错了什么?

我想避免抛出一个i = NOTANINTEGER停止循环

for (var i=0; i< 100; i++)
  {
    var breakForLoop = false;
    var API = "http://www.foo.com/bar.json?page=" + i;

    $.getJSON(API,  function(data) {
      var items = {};
      // logs items from page run only when the page has data
      if (data.length > 0) {
        $.each( data, function(i, item) {
          console.log(item.text);
        });
      }
      // the page has no data, therefore remainder pages have no data too
      else {
        console.log("this page has no content");
        breakForLoop = true;
        return;
      }
    });

   if (breakForLoop) {
       break;
   }
}
4

1 回答 1

3

一种可能的解决方案是使用类似的东西

//this method tries to fetch data from page `x`, if there is data in the current page then it will again try to fetch data from page `x + 1`
function fetchData(page) {
    page = page || 0;
    var API = "http://www.foo.com/bar.json?page=" + page;

    $.getJSON(API, function (data) {
        var items = {};
        // logs items from page run only when the page has data
        if (data.length > 0) {
            $.each(data, function (i, item) {
                console.log(item.text);
            });
            //since there is data in the current page try to fetch data from page page + 1
            fetchData(page + 1);
        }
        // the page has no data, therefore remainder pages have no data too
        else {
            console.log("this page has no content");
        }
    });
}

//initiage fetching data
fetchData(0) ;
于 2013-11-03T16:49:16.503 回答