如何正确地实现一个自定义的AJAX自定义、正确地、AJAX

2023-09-10 19:07:14 作者:你是我触摸不到的若即若离

为了保持logotext < D​​IV CLASS =小7中4列标志> 键,菜单<导航类=pagedMenu角色=导航> ,不削波刷新页面或在内容从一个页面到另一个加载,我试图实施该解决方案通过的 @Buzinas (特别感谢)。在几句话:

In order to keep the logotext <div class="small-7 medium-4 columns logo"> and the menu <nav class="pagedMenu" role="navigation">,without clipping on page refresh or while the content is loading from a page to another, I am trying to implement this solution made by @Buzinas (special thanks). In a few more words:

的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 注册/入队中的脚本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() 功能如下:

Also, in page.php I replaced get_header() and get_footer() functions as follows:

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

目前还有一些问题试图加载一个页面,革命滑块或Visual Composer的视差的内容,就像我们对视差或关于我们的网页为例。

您可以使用此链接并导航到上面提到的页面;测试只在Chrome浏览器取得了45.0.2454.101米64位/ Win7的,尚未$ P ppared的IE浏览器,火狐,$移动等。

You can use this link and navigate to the above mentioned pages; Tests are made only in Chrome 45.0.2454.101 m 64-bit/ Win7, not yet prepared for IE, Firefox, mobile etc .

关于行为: 启滑块视差的内容,将通过第二个链接访问加密(首页或视差的页面);在可视化编辑器视差的内容(这家伙在办公桌上的画面,关于我们的页面为例)被固定在第一个环节考察 - 后F5将被罚款;

About the behaviour: Rev slider parallax content, will become scrambled from the second link visit (Home or Parallax pages); The Visual Composer parallax content (the guy at the desk picture, About us page for example) is fixed on the first link visit - after F5 will be fine;

菜单 mynewmenu.js 会记住会话状态的 的,所以日子会把你必须关闭浏览器在奥德正常访问多个直接联系。

The menu mynewmenu.js will remember the state on session, so u'll have to close the browser in oder to visit multiple direct links properly.

我收到了来自启滑盖支持团队告诉我一个答案:

I've received an answer from Rev slider support team telling me:

适合于Ajax的最好的办法是只需要添加滑块的短code到正规页/后,然后将滑块的初始化的脚本将自动包含与滑块的HTML。然后,当滑块的HTML是从DOM中删除,所有的jQuery的事件也将被删除。所以,你真正需要做的是拉在滑块的页面/后的内容,那么你将不再需要为滑块专门任何自定义脚本。的

不幸的是我不知道我该怎么处理这个,实现上述sugestion到我已经接受的解决方案。

Unfortunately I have no idea how can I approach this, implementing the above sugestion into my already received solution.

可能是一些相关的API(?)我发现这些相关信息在革命滑块 / < A HREF =htt​​ps://wpbakery.atlassian.net/wiki/display/VC/Inner+API>视觉作曲家页面。有什么想法?

Could be something related to API(?) I've found these infos on Revolution slider / Visual Composer pages. Any thoughts?

推荐答案

它看起来像你这样在你走之前的codeS乱搞,你需要知道如何变化将会使用一个字preSS主题以实现该网站。

It looks like you are using a WordPress Theme so before you go messing around with the codes you need to know how changes are going to effect the website.

我建立一个PHP的网站的方式是我的头包含在PHP文件 并使用检索到

The way I build a PHP website is my header is contained in a PHP file and is retrieved using

<?php include('include/header.php'); ?> 

您正在使用(PHP)服务器端脚本来检索使用客户端脚本数据库中的信息,至少这是它如何出现。一个可能的解决方案可能是重写你的头和移动Java脚本到外部文件

You are using (PHP) server side scripting to retrieve the information from a database using client side scripting, at least that is how it appears. A possible solution may be to rewrite your header and move the java script to an external file