2017-04-26 10 views
0

나는 내가 만든 WordPress Plugin과 대화를 한 embedding 가능한 JavScript 위젯을 가지고있다. 기본적으로 위젯은 사용자 정의 WP API 엔드 포인트를 호출하고 JSON을 가져 와서 카테고리 인 제품의 피드를 빌드합니다. 카테고리를 클릭 할 때마다 새 API 호출을 통해 다음으로 드릴 다운하여 새 데이터를 가져옵니다.Ajax 앱 API 호출에서 HTML5 기록을 사용하는 방법은 무엇입니까?

모두 작동하지만 예전 브라우저를 다시 작동시키는 방법을 알아 내려고 노력하고 있습니다.

쉬운 해시뱅크 일지라도 상관 없으며, 북마크하거나 Google 크롤링 할 필요가 없습니다.

자습서 나는 pushState가 객체라고하지만, 무엇을 의미합니까?

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 것 :

내 클릭 핸들러는

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

}); 

각각의 경우 데이터 출력을 얻을 다른 아약스 호출 예로 이동, 다음과 같습니다 .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; 
     } 
}); 

작업 틱 알았어요. 이것은 해시를 통해 처리되지 않기 때문에 처음에는 doc 준비에서 ajax 호출을 통해로드 되었기 때문입니까?

+0

전화 수동 기능이 처음. 그것은'var hashFn = function() {...}'입니다. '$ (윈도우) .on ('hashchange', hashFn)'. 'hashFn()'. 그런 다음 linkType/linkId가 설정되지 않은 경우 ('split.length <2'인 경우) 기본 코드를 추가하십시오. – FrankerZ

답변

0

1 단계 : switch 문 대신 window.location.hash = "#categories-" + id;을 추가하십시오.

/*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 처리기를 추가 해시 (. 즉, # 범주-1) URL의 변경 :

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

고맙습니다. 'let'은 무엇입니까? – thatryan

+0

이 시작 주셔서 감사합니다, 올바른 방향으로 저를 잡았습니다, 새로운 질문으로 업데이트 된 코드 :) – thatryan

관련 문제