【问题标题】:How to send wordpress category as data to ajax? [closed]如何将wordpress类别作为数据发送到ajax? [关闭]
【发布时间】:2015-05-11 19:00:58
【问题描述】:

我想将页面的当前类别发送到 ajax。我正在为我的博客网站使用 WordPress。我想将当前页面类别发送到 infi.php,但我不知道该怎么做。

我的 ajax

$.ajax({
        type: "POST",
        async: false,
        url: "/infi.php",
        data: {pcount:post_page_count},
        success:
        function(result){
            $("#gizinfi").append(result);
            }
      });

【问题讨论】:

  • async:false 已弃用,不应使用
  • 感谢您的提示 charlietfl
  • 页面无法分类。帖子可以分类
  • 我可以将分类页面分类 id 发送到 ajax 吗?

标签: php jquery ajax wordpress post


【解决方案1】:

要在 Wordpress 中正确使用 AJAX,您需要执行几个步骤。

首先,假设您正在正确注册和排队 javascript 文件(如果您不知道或不知道这意味着您应该查看如何在 Wordpress 中将文件排队),您需要本地化文件。在您的 functions.php 文件中,您可以像这样本地化一个文件...

$data_array = array(
    'ajaxurl' => admin_url( 'admin-ajax.php' )
);

wp_register_script( 'YourAjaxScript', get_template_directory_uri() . 'js/example.js', array('jquery') );
wp_localize_script( 'YourAjaxScript', 'myAjax', $data_array );

现在您需要通过某种方式从您的 javascript 中访问类别 ID。您可以简单地在模板中的某处包含一个空跨度并将您的 category_id 存储为数据属性,然后您可以使用 javascript 轻松找到它。出于安全原因,您还可以添加“nonce”,这允许您检查访问 PHP 的是您的 ajax 调用,而不是随机数。所以我们将把它添加到你的 header.php...

<?php
//For the sake of this we'll only get the first category
$categories = get_the_category();
$cat = ( !empty( $categories ) ? $categories[0]->term_id : false );

//We'll also create a nonce for security
$nonce = wp_create_nonce( 'ajax_nonce' );
?>

<span id="category-id" data-category="<?php echo $cat; ?>" data-nonce="<?php echo $nonce; ?>"></span>

现在您可以在您的 example.js 文件中创建您的 AJAX 函数...

$( document ).ready( function() {

    //Fetch your data variables
    var $cat = $( '#category-id' ).data('category');
    var $nonce = $( '#category-id' ).data('nonce');

    $.ajax({
        type: 'POST',
        url: myAjax.ajaxurl,
        data: {
            action: 'my_ajax_handler', //PHP function to handle AJAX request
            category: cat,
            nonce: $nonce
        },
        success: function( data ) {
            $("#gizinfi").append( data );
        }
    });

});

然后您需要创建一个 PHP 函数来处理您的 AJAX 请求(可以放入您的 infi.php 文件,只要您正确包含该文件,但在您的 functions.php 文件中可能会更好)。比如……

/**
 * my_ajax_handler - handles my ajax response and returns some data
 * @return string - my data
 */
function my_ajax_handler() {
    //First we'll validate the nonce and exit if incorrect
    if ( !wp_verify_nonce( $_POST['nonce'], 'ajax_nonce' ) ) { exit; }

    //Here we handle your ajax request and return whatever
    //All our data variables are saved in the $_POST array
    $category = $_POST['category'];
    return $category;
}

add_action("wp_ajax_my_ajax_handler", "my_ajax_handler");
add_action("wp_ajax_nopriv_my_ajax_handler", "my_ajax_handler");

最后两行将函数绑定到您的 ajax 调用。这应该就是您所需要的。

希望有帮助

【讨论】:

  • 学习需要时间,但现在可以使用了...谢谢您的帮助 danbahrami
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 1970-01-01
相关资源
最近更新 更多