【问题标题】:datasource failing to map to the transformed json using pagination数据源无法使用分页映射到转换后的 json
【发布时间】:2021-07-21 18:14:47
【问题描述】:

我正在使用pagination.js 使用下面的代码 sn-p 加载异步数据。

$('#demo').pagination({
    dataSource: 'https://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?',
    locator: 'items',
    totalNumber: 120,
    pageSize: 20,
    ajax: {
        beforeSend: function() {
            dataContainer.html('Loading data from flickr.com ...');
        }
    },
    callback: function(data, pagination) {
        // template method of yourself
        var html = template(data);
        dataContainer.html(html);
    }
})

由于我的json结构不同,我需要在将json映射到datasource之前进行转换,所以我把上面的代码改成如下图:

$('#demo').pagination({
      dataSource: getTransformedJson(),
      locator: 'items',
      totalNumber: 120,
      pageSize: 25,
      ajax: {
        beforeSend: function() {
          container.prev().html('Loading products data ...');
        }
      },
      callback: function(response, pagination) {
        var dataHtml = '<ul>';
          console.log('response', response)
        $.each(response, function (index, item) {
          dataHtml += '<li>' + item.productName + '</li>';
        });

        dataHtml += '</ul>';

        container.prev().html(dataHtml);
      }
    })
  });

但是在回调中,console.log('response', response) 总是在浏览器控制台中显示空数组response []。下面是我的getTransformedJSON() 函数:

function getTransformedJson() {
      $.getJSON('./products.json', function(data) {         
        transformedData = data;
        totalCount = data['response']['totalCount'];
        transformedData['items'] = data['response']['results'];
        delete transformedData['response']["results"];
        console.log(transformedData);
          });

          return transformedData;
    }

但是在我的getTransformedJson() 函数中,console.log(transformedData); 显示了正确转换的 json 数据。请对此进行任何修复。

【问题讨论】:

  • $.getJSON 是异步的。您的函数在 $.getJSON 完成之前返回。
  • svela,我如何确保函数在 $.getJSON 完成之前不会结束,或者如何确保我的数据源将正确映射转换后的 json
  • 请在下方找到我的答案

标签: javascript jquery ajax pagination jquery-pagination


【解决方案1】:

类似这样的:

dataSource: function(done) {
    $.getJSON('./products.json', function(data) {         
        transformedData = data;
        totalCount = data['response']['totalCount'];
        transformedData['items'] = data['response']['results'];
        delete transformedData['response']["results"];
        done(transformedData);
     });

          
 }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2017-12-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多