简体   繁体   English

如何在Ajax应用程序API调用中使用HTML5历史记录?

[英]How to use HTML5 history with Ajax app API calls?

I have an embeddable JavScript widget I have made that talks to a WordPress Plugin I made. 我有一个嵌入的JavScript小部件,可以与我制作的WordPress插件进行对话。 Basically the widget calls out out to some custom WP API endpoints and gets the JSON back then builds a feed of products that are categories. 基本上,小部件会调出一些自定义WP API端点,并返回JSON,然后构建属于类别的产品的供稿。 Each click on category drills down to next via a new API call to get new data. 每次单击类别都会通过新的API调用向下钻取下一个以获取新数据。

It all works, yay, but I am having a heck of a time trying to figure out how to make browser back button work. 是的,所有的方法都有效,但是我花了很长时间试图弄清楚如何使浏览器后退按钮起作用。

Note that I do not care if it can be an easy hashbang or whatever, this does not need to be bookmarkable or google crawlable. 请注意,我不在乎它是否可以是简单的hashbang或其他,它不需要是可书签的或Google可检索的。

Tutorials I find just say pushState is an object, but of what? 我发现教程只是说pushState是一个对象,但是什么呢?

My click handler looks like this, 我的点击处理程序看起来像这样,

$('#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;
          }

});

Each case goes to a different ajax call, that gets the data and outputs it, example: 每种情况都会转到不同的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);
    });
}

Now would pushState happen in the .done() chain, and if so what gets added there? 现在,pushState将发生在.done()链中,如果是的话,在那里添加了什么?

Any tips are greatly appreciated, thank you! 任何提示,不胜感激,谢谢!

update 更新

Got it working-ish with this 与此一起工作

$(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;
      }
});

However fails when going back to "first" page. 但是,当返回“第一”页面时失败。 Is this because it is not handled via a hash and is initially loaded via an ajax call on doc ready? 这是因为它不是通过散列处理的,而是最初通过对文档就绪的Ajax调用加载的吗?

Step 1: Add window.location.hash = "#categories-" + id; 步骤1:添加window.location.hash = "#categories-" + id; instead of the switch statement. 而不是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.

Step 2: Add an onhashchange handler which will fire any time the hash (ie. #categories-1) changes in the URL: 第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;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM