WordPress 中的 jQuery 帖子

Eli*_*ian 2 ajax wordpress jquery

我的 WP 主题的 JS 文件夹内的 JS 文件中有以下代码:

jQuery('#tarieven-submit').on('click', function(event) {
    event.preventDefault();

    var dest = jQuery('#destination').val();
    var type = jQuery('input[name=taxiType]:checked', '#distance_form').val()

    if (jQuery.trim(dest) != '' && type != '') {
        jQuery.post('../HTA/wp-content/themes/HTA/ajax/tarieven.php', { destination: dest, type: type}, function(data) {
            jQuery('#result').text(data);
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

即使发布到的文件位于正确的文件夹中,我也无法使其正常工作。我猜它与错误的 AJAX 调用有关。但我似乎无法找到如何正确执行此操作。例如,我已经看到我需要在 admin-ajax.php 中进行 AJAX 调用,但是,如何在那里添加我的自定义代码?

Ale*_*pez 7

您应该尝试使用 WordPress 标准进行 AJAX 调用,要创建 AJAX 调用,您只需在functions.php文件中添加将处理您的调用的 PHP 函数,例如,

function ajax_handler() {
    // Do your stuff here;

    wp_die(); // Always put this at the end, it is required by WordPress to end your call.
}
Run Code Online (Sandbox Code Playgroud)

然后你用这个注册你的 AJAX 操作。

add_action( 'wp_ajax_ajax_handler', 'ajax_handler' );
add_action( 'wp_ajax_nopriv_ajax_handler', 'ajax_handler' ); // This is for unlogged users.
Run Code Online (Sandbox Code Playgroud)

所以,你的 jQuery 函数应该是这样的:

var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; // This is the WordPress AJAX handler file.

jQuery('#tarieven-submit').on('click', function(event) {
event.preventDefault();
var dest = jQuery('#destination').val();
var type = jQuery('input[name=taxiType]:checked', '#distance_form').val()
if (jQuery.trim(dest) != '' && type != '') {
    jQuery.post(ajaxurl, { destination: dest, type: type, action: "ajax_handler"}, function(data) {
        jQuery('#result').text(data);
    });
}
Run Code Online (Sandbox Code Playgroud)

请注意action我们发送到 WordPress AJAX 处理程序文件 (admin-ajax.php) 的参数。需要告诉 WordPress 在我们的调用中应该执行哪个函数/动作。