programing

커스텀 에이잭스를 적절히 구현하는 방법

subpage 2023. 2. 23. 22:49
반응형

커스텀 에이잭스를 적절히 구현하는 방법

logotext를 하기 <div class="small-7 medium-4 columns logo"> and menu menu and and 。<nav class="pagedMenu" role="navigation">페이지 리프레시 시 클리핑 없이, 또는 페이지에서 다른 페이지로 콘텐츠를 로드하는 동안, 저는 @Buzinas에서 만든 이 솔루션을 구현하려고 합니다(특별히 감사합니다.몇 마디 더 하자면:

»header.php하다

<head>
    ...

    <script>
    function ajax(url, callback, method, params) {
      if (!method) method = 'GET';

      var xhr = new XMLHttpRequest();
      xhr.open(method, url);

      if (callback) xhr.addEventListener('load', function() {
        callback.call(this, xhr);
      });

      if (params) {
        params = Object.keys(params).map(function(key) {
          return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
        }).join('&');
        xhr.send(params);
      } else {
        xhr.send();
      }
    }

    // CUSTOM AJAX CONTENT LOADING FUNCTION
    function ajaxRevslider(obj) {

        // obj.type : Post Type
        // obj.id : ID of Content to Load
        // obj.aspectratio : The Aspect Ratio of the Container / Media
        // obj.selector : The Container Selector where the Content of Ajax will be injected. It is done via the Essential Grid on Return of Content

        var content = "";

        data = {};

        data.action = 'revslider_ajax_call_front';
        data.client_action = 'get_slider_html';
        data.token = '<?php echo wp_create_nonce("RevSlider_Front"); ?>';
        data.type = obj.type;
        data.id = obj.id;
        data.aspectratio = obj.aspectratio;

        // SYNC AJAX REQUEST
        jQuery.ajax({
            type:"post",
            url:"<?php echo admin_url('admin-ajax.php'); ?>",
            dataType: 'json',
            data:data,
            async:false,
            success: function(ret, textStatus, XMLHttpRequest) {
                if(ret.success == true)
                    content = ret.data;                             
            },
            error: function(e) {
                console.log(e);
            }
        });

         // FIRST RETURN THE CONTENT WHEN IT IS LOADED !!
         return content;                         
    };

    // CUSTOM AJAX FUNCTION TO REMOVE THE SLIDER
    function ajaxRemoveRevslider(obj) {
        return jQuery(obj.selector+" .rev_slider").revkill();
    }

    document.addEventListener('DOMContentLoaded', function() {
      var main = document.querySelector('div[role=main]'),
        spinner = document.querySelector('div.sk-spinner'),
        pages = {};

      window.addEventListener('load', function() {
          toggleSpinner(false);
      });

      function toggleSpinner(b) {       
        spinner.classList[b ? 'remove' : 'add']('hidden');
        document.getElementById('wrapper').style.opacity = b ? 0 : 1;
      }

      function changePage(url, title) {
        setTimeout(function() {
          window.SITE.init();
          window.vc_js();
        }, 0);

        history.pushState({
          html: main.innerHTML,
          title: title
        }, '', url);

        toggleSpinner(false);
      }

      document.getElementById('menu-menu-2').addEventListener('click', function(e) {
        var el = e.target;

        if (el.tagName === 'A') {
          e.preventDefault();
          toggleSpinner(true);

          if (pages[el.href]) {
            main.innerHTML = '';
            main.appendChild(pages[el.href]);
            changePage(el.href);
          }
          else {
            ajax(el.href, function(xhr) {
              var frag = document.createRange().createContextualFragment(xhr.responseText);
              main.innerHTML = '<div>' + frag.querySelector('div[role=main]').innerHTML + '</div>';
              //pages[el.href] = main.firstElementChild;

              var _currentScripts = [].slice.call(document.querySelectorAll('script'));

              [].forEach.call(frag.querySelectorAll('script'), function(el, i) {
                if ((el.src === '' && el.parentNode)
                    || el.src.indexOf('slider') >= 0
                    || el.src.indexOf('Scroll') >= 0
                    || el.src.indexOf('vendor') >= 0
                    || el.src.indexOf('composer') >= 0
                   ) {
                  var s = _currentScripts.filter(function(x) {
                    return x.src === el.src;
                  });

                  while (s.length) {
                    if (s[0].parentNode)
                      s[0].parentNode.removeChild(s[0]);
                    s.shift();
                  }

                  document.body.appendChild(el);
                }
              });

              [].forEach.call(frag.querySelectorAll('style'), function(el, i) {
                document.querySelector('head').appendChild(el);
              });

              changePage(el.href, frag.querySelector('title').textContent);
            });
          }
        }
      });

      window.addEventListener('popstate', function(e) {
        if (e.state) {
          main.innerHTML = e.state.html;
          document.title = e.state.title;
        }
      });
    });
    </script>

    ...
</head>

와 같다jquery-ready.js is is에 등록/ 있습니다.script-calls.php:

(function($){
var readyList = [];

// Store a reference to the original ready method.
var originalReadyMethod = jQuery.fn.ready;

// Override jQuery.fn.ready
jQuery.fn.ready = function(){
    var args = [].slice.call(arguments);

    if(args.length && args.length > 0 && typeof args[0] === 'function') {
      readyList.push(args[0]);
    }

    // Execute the original method.
    originalReadyMethod.apply( this, args );
};

// Used to trigger all ready events
$.triggerReady = function() {
  $(readyList).each(function(i, el) {
      try {
          el.apply(el);
      } catch(e) {
          console.log(e);
      }
  });
};
})(jQuery);

, 、 인 。page.php교체했습니다.get_header() ★★★★★★★★★★★★★★★★★」get_footer()의 기능은 과 같습니다

<?php
if(!isset($_REQUEST['ajax'])){
    get_header(); 
}
?>
<?php 
    if (is_page()) {
        $id = $wp_query->get_queried_object_id();
        $sidebar = get_post_meta($id, 'sidebar_set', true);
        $sidebar_pos = get_post_meta($id, 'sidebar_position', true);
    }
?>
...

<?php
if(!isset($_REQUEST['ajax'])){
    get_footer();
}
?>

예를 들어 ParallaxAbout us 페이지와 같이 Revolution 슬라이더 또는 Visual Composer Parallax 콘텐츠가 포함된 페이지를 로드하려고 하면 여전히 문제가 발생합니다.

링크를 사용하여 위의 페이지로 이동할 수 있습니다.테스트는 Chrome 45.0.2454.101m 64비트/Win7에서만 수행되며 IE, Firefox, 모바일 등은 아직 준비되지 않았습니다.

동작에 대해서: Rev 슬라이더 시차 콘텐츠가 두 번째 링크 방문부터 스크램블됩니다( 페이지 또는 시차 페이지).Visual Composer의 시차 콘텐츠(데스크 그림의 About us 페이지 등)는 첫 번째 링크 방문 시 수정됩니다.F5 이후에는 문제가 없습니다.

메뉴는 세션 상태를 기억하기 때문에 여러 다이렉트 링크를 올바르게 방문하려면 브라우저를 닫아야 합니다.

Rev 슬라이더 지원팀으로부터 다음과 같은 답변을 받았습니다.

Ajax의 가장 좋은 옵션은 일반 페이지/포스트에 슬라이더의 쇼트 코드를 추가하는 것입니다. 그러면 슬라이더의 HTML에 슬라이더의 "init" 스크립트가 자동으로 포함됩니다. 그런 다음 슬라이더의 HTML이 DOM에서 제거되면 모든 jQuery 이벤트도 제거됩니다.따라서 슬라이더를 페이지/포스트 콘텐츠로 끌어오면 슬라이더에 대해 특별히 커스텀스크립트가 필요하지 않습니다.

유감스럽게도 어떻게 접근해야 할지 모르겠습니다.이러한 제안을 이미 받은 솔루션에 구현합니다.

API(?)와 관련된 것일 수 있습니다. 이러한 infos는 Revolution 슬라이더 / Visual Composer 페이지에서 찾을 수 있습니다.무슨 생각 있어?

다음 내용을 읽어야 합니다.

를 사용하여 PHP 변수를 javascript 파일로 전달해야 합니다.

이렇게 하지 않더라도 특정 콘텐츠를 제공하기 위해 메인 페이지 템플릿을 해킹할 필요는 없습니다.단일 페이지를 작성한 후 특정 템플릿을 만듭니다.그런 다음 해당 페이지의 URL을 Ajax 끝점으로 사용할 수 있습니다.

그러나 Rev Slider의 단축코드(및 Parallax가 있는 경우)를 페이지가 아닌 다른 곳에서 실행해야 하는 경우:

아직도 도움이 필요하세요?혁명 슬라이더의 지원팀이 그 진술로 그것을 해결했다고 생각한다.

슬라이더의 쇼트 코드를 일반 페이지/게시판에 추가하기만 하면 됩니다.

그리고.

슬라이더를 페이지/포스트 콘텐츠로 끌어당기기만 하면 됩니다.

따라서 WordPress 페이지/게시판의 슬라이더를 쇼트 코드인 [숏 코드]로 사용합니다.그런 다음 필요에 따라 php(또는 javascript, 그러나 실행 중인 경우)의 $_GET[] 및/또는 $_POST[] 배열 요소를 참조합니다.

언급URL : https://stackoverflow.com/questions/33087632/how-to-properly-implement-a-custom-ajax

반응형