要在 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 调用。这应该就是您所需要的。
希望有帮助
丹