如何在Ajax app API调用中使用HTML5历史记录?

时间:2017-04-26 17:28:13

标签: javascript ajax html5-history

我有一个可嵌入的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;
      }
});

然而,当回到&#34;首先&#34;页。这是因为它不是通过哈希处理的,最初是通过doc ready a上的ajax调用加载的吗?

1 个答案:

答案 0 :(得分:0)

步骤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;
      }
}