AJax技术

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

字号+ 作者:H5之家 来源:H5之家 2017-04-10 18:02 我要评论( )

如何正确地实现一个自定义的AJAX(How to properly implement a custom ajax) - IT屋-程序员软件开发技术分享社区

问 题

In order to keep the logotext <div> and the menu <nav 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:

In header.php we have this script:

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

The following jquery-ready.js is registered/enqueued in 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);

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

There are still some issues trying to load a page with Revolution slider or Visual Composer Parallax content, like we have on Parallax or About us pages for example.

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 .

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • 在JavaScript的jQuery库中操作AJAX的方法讲解【站长博客网】

    在JavaScript的jQuery库中操作AJAX的方法讲解【站长博客网】

    2017-04-09 16:00

  • 求赞,关于$this-success()方法的小技巧

    求赞,关于$this-success()方法的小技巧

    2017-04-08 12:01

  • PHP 实现ajax Loading加载功能

    PHP 实现ajax Loading加载功能

    2017-04-07 14:03

  • Ajax基础与登入教程

    Ajax基础与登入教程

    2017-04-06 16:04

网友点评