【问题标题】:How to use HTML5 history with Ajax app API calls?如何将 HTML5 历史记录与 Ajax 应用程序 API 调用一起使用?
【发布时间】:2017-04-26 17:28:12
【问题描述】:

我制作了一个可嵌入的 JavScript 小部件,它与我制作的 WordPress 插件对话。基本上,小部件调用一些自定义 WP API 端点并获取 JSON,然后构建类别产品的提要。每次点击类别都会通过新的 API 调用深入到下一个以获取新数据。

一切正常,是的,但我有一段时间试图弄清楚如何使浏览器后退按钮起作用。

请注意,我不在乎它是否可以是简单的 hashbang 或其他什么,它不需要是可收藏的或可被 Google 抓取的。

我发现教程只是说 pushState 是一个对象,但是是什么?

我的点击处理程序看起来像这样,

$('#sqsl_products').on('click', '.ssla-embed-link',  function( e ) {
   e.preventDefault();
      var link = $(this),
          linkType = link.attr('data-link_type'),
          linkId = link.attr('data-link_id');

          switch( linkType ) {
              case 'categories':
                  getCategories( linkId );
                  break;
              case 'products':
                  getProducts( linkId );
                  break;
              case 'product':
                  getProduct( linkId );
                  break;
          }

});

每个案例都进行不同的 ajax 调用,获取数据并输出,例如:

function getCategories( id ) {
    $.ajax({
        method: 'GET',
        url: apiUrl + '/categories',
        beforeSend: function() {
            $(domTag).prepend('<div class="ssla-loading-top"></div>');
        },
        dataType: 'json',
        data: { categories: id },
    })
    .done(function( response ) {
        var catList = '<ul>';
        var brand = response.brand;
        $.each(response.data, function () {
            catList += '<li><a data-link_type=' + this.type + ' data-link_id=' + this.id + ' class="ssla-embed-link" href="#' + this.id + '"><img src="'+this.image+'"/>' + this.name + '</a></li>';
        });
        catList += '</ul>';
        $(domTag).removeClass().addClass( 'ssla-' + brand + ' ssla-categories' ).html(catList);
    })
    .fail(function( jqXHR ) {
        var json = $.parseJSON(jqXHR.responseText);
        $(domTag).removeClass().addClass('ssla-error').html(json.message);
        console.log(jqXHR);
    });
}

现在 pushState 会发生在 .done() 链中,如果是这样,那里会添加什么?

非常感谢任何提示,谢谢!

更新

用这个可以正常工作

$(window).on('hashchange', function( e ) {

    var hash = document.URL.substr(document.URL.indexOf('#')+1);
    var split = hash.split('-');
    if ( split.length < 2 ) {
        return;
    }
    var linkType = split[0];
    var linkId = split[1];

    console.log(linkType);
    console.log(linkId);

      switch( linkType ) {
          case 'categories':
              getCategories( linkId );
              break;
          case 'products':
              getProducts( linkId );
              break;
          case 'product':
              getProduct( linkId );
              break;
      }
});

但是返回“第一”页时失败。这是因为它不是通过哈希处理,而是最初通过 ajax 调用对 doc 就绪进行加载吗?

【问题讨论】:

  • 第一次手动调用函数。它var hashFn = function() {...}$(window).on('hashchange', hashFn)hashFn()。然后如果没有设置linkType/linkId,(你在哪里if split.length &lt; 2),添加默认代码。

标签: javascript ajax html5-history


【解决方案1】:

第 1 步:添加 window.location.hash = "#categories-" + id; 而不是 switch 语句。

/*switch (linkType) {
    case 'categories':
        getCategories(linkId);
        break;
    case 'products':
        getProducts(linkId);
        break;
    case 'product':
        getProduct(linkId);
        break;
}*/
//Replace the switch function. This will update the url to something like #categories-1 which will fire the event below
window.location.hash = '#' + linkType + '-' + linkId;
//Optionally, you can just set the href of the URL's to #categories-1 instead of using this function at all.

第 2 步:添加一个 onhashchange 处理程序,该处理程序将在 URL 中的哈希(即 #categories-1)更改时触发:

$(window).on('hashchange', function( e ) {
      let split = window.location.split('-');
      if ( split.length < 2 )
         return;

      var linkType = split[0];
      var linkId = split[1];

      switch( linkType ) {
          case 'categories':
              getCategories( linkId );
              break;
          case 'products':
              getProducts( linkId );
              break;
          case 'product':
              getProduct( linkId );
              break;
      }
}

【讨论】:

  • 谢谢,我试试看。 let 是什么?
  • 感谢您的开始,我认为让我朝着正确的方向前进,用新问题更新了代码 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-06
  • 1970-01-01
  • 2017-02-25
  • 2020-01-19
  • 2018-04-06
  • 1970-01-01
相关资源
最近更新 更多