【问题标题】:Wordpress Ajax TechniquesWordPress Ajax 技术
【发布时间】:2012-04-14 09:59:05
【问题描述】:

我最近一直在尝试在 WordPress 中实现 AJAX。我知道有很多插件可用,但我想自己制作。

在有关 AJAXified WordPress 的文章中,大多数人建议使用 admin-ajax.php 来处理 AJAX 请求。我的第一个想法是简单地创建自定义 get_header() 和 get_footer()

第一种方式

// Boolean function ?ajax=true
function is_ajax () {
  if($_REQUEST['ajax']) {
    return true;
  } else {
    return false;
  }
}

function ajax_get_header () {
  if(is_ajax()) {
    get_header('ajax'); 
    /* Insert header-ajax.php which
    includes only google analytics tracking code and some minor stuff */
    return true;
  } else {
    get_header();  
    // Standard header
    return true;
  }
}

/* Function ajax_get_footer() pretty much the same */

然后,页面模板看起来像

<?php ajax_get_header(); ?>

<!-- Content -->

<?php ajax_get_footer(); ?>

当然,使 ajax 调用成为标准方式。 这种方法看起来简单而干净。 另一方面,很多人建议使用内置函数,通过创建一个钩子来捕获 AJAX 调用。

第二种方式

function process_ajax(){
  /* Show the page or whatever */
}
add_action('wp_ajax_nopriv_ajax', 'process_ajax');
add_action('wp_ajax_ajax', 'process_ajax');

并将 AJAX 调用指向 admin-ajax.php

使用哪一个?

我已经尝试了这两种方法,发现第一种方法的加载速度比后一种方法快得多。在相同条件下,第一种方式(ajax_get_header)大约需要 400 毫秒来加载页面(几乎没有内容),第二种方式(admin-ajax.php)大约需要 800 毫秒。我不知道为什么,两种方式都加载 WP 核心并且做的事情几乎相同。

那么,我在问你,是否有充分的理由通过 admin-ajax.php 进行 AJAX 调用?是必要的吗?以及为什么通过推荐的方式处理呼叫需要更多时间?

【问题讨论】:

标签: php jquery ajax wordpress


【解决方案1】:

您的第一种方式总是比 Wordpress 自己的 ajax 更快,因为 admin-ajax.php 会处理许多其他事情,例如 核心管理挂钩 和其他函数调用,这反过来又构成了整体ajax 调用非常庞大。

在第一种方式中,除了自己的功能和输出之外,您无需担心其他任何事情。这提高了性能。

使用什么没有硬性规定,第一种方法可以更快地做事,但它们不能与 wordpress 的核心管理功能挂钩,这对于某些目的可能是不利的。

查看 admin-ajax.php

$core_actions_get = array(
'fetch-list', 'ajax-tag-search', 'wp-compression-test', 'imgedit-preview', 'oembed-cache',
'autocomplete-user', 'dashboard-widgets', 'logged-in',
);

$core_actions_post = array(
'oembed-cache', 'image-editor', 'delete-comment', 'delete-tag', 'delete-link',
'delete-meta', 'delete-post', 'trash-post', 'untrash-post', 'delete-page', 'dim-comment',
'add-link-category', 'add-tag', 'get-tagcloud', 'get-comments', 'replyto-comment',
'edit-comment', 'add-menu-item', 'add-meta', 'add-user', 'autosave', 'closed-postboxes',
'hidden-columns', 'update-welcome-panel', 'menu-get-metabox', 'wp-link-ajax',
'menu-locations-save', 'menu-quick-search', 'meta-box-order', 'get-permalink',
'sample-permalink', 'inline-save', 'inline-save-tax', 'find_posts', 'widgets-order',
'save-widget', 'set-post-thumbnail', 'date_format', 'time_format', 'wp-fullscreen-save-post',
'wp-remove-post-lock', 'dismiss-wp-pointer', 'upload-attachment',
);

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 2012-08-29
    • 2010-10-31
    • 2019-05-28
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多