【问题标题】:Include PHP file via AJAX call通过 AJAX 调用包含 PHP 文件
【发布时间】:2018-03-27 01:36:20
【问题描述】:

我正在尝试通过 ajax 请求调用位于插件子文件夹中的 .php 文件。我尝试了很多不同的包含方法,包括 get_template_part,但我似乎无法获得要呈现的内容。我觉得我可能做错了,但我不确定下一步该尝试什么。该文件位于上面的一个目录中,然后位于另一个名为“模板”的目录中。

tps_show_modal 是自定义函数,第二个参数是模态框的内容。 (此功能已确认在其他地方工作)。

感谢任何帮助。

PS。我还需要将变量 (spaceID) 传递给包含的文件,因此使用 set_query_var()
PPS。 工作在 Wordpress 环境中

这是我的 ajax 请求:

$(document).on('click', '.uiSpaceTitle', function(e) {
    var spaceID = $(this).attr('data-spaceid');
    $.ajax({
        type : 'post',
        dataType : 'json',
        url : myAjax.ajaxurl,
        context : this,
        data: {
            action: 'tps_get_space_info_block_ajax', spaceID:spaceID
        },
        success: function(response) {
            console.log(response);
            var wWidth = $(window).width();
            var dWidth = wWidth * 0.8; //this will make the dialog 80% of the window
            tps_show_modal('Space Info', response, false, 'OK', dWidth);
        }
    });

    e.preventDefault();
});

这是我调用的 php 函数:

add_action('wp_ajax_tps_get_space_info_block_ajax', 'tps_get_space_info_block_ajax');
add_action('wp_ajax_nopriv_tps_get_space_info_block_ajax', 'tps_get_space_info_block_ajax');
function tps_get_space_info_block_ajax() {
    set_query_var('spaceID', $_REQUEST['spaceID']);
    ob_start();
    include('../templates/space-info-pane.php');
    $result = ob_get_clean();
    $result = json_encode($result);
    echo $result;
    die();
}

【问题讨论】:

  • 在你的 ajax 成功函数之后添加 this: succes: function(response){ ... }, error: function(e, t, a) { console.log(e) } 并告诉我是否有事
  • 感谢您的帮助。添加时,我在控制台中看不到任何内容。
  • 好的,如果您在函数中评论内容并添加任何内容的回声,它会显示吗?
  • 是的,但实际包含仍然没有运气。我检查了文件路径,我相信我使用了正确的包含语法?
  • 如果不立即执行包含,而是创建一个调用该包含的函数,并在 ob_start("newFunctionWithThe Include") 中将该函数作为回调调用呢?您可以试试吗? ?

标签: php jquery ajax wordpress include


【解决方案1】:

答案是,在插件中包含文件时,Wordpress 很奇怪。我不得不使用它而不是普通的包含文件路径:

include(plugin_dir_path( __DIR__ ).'templates/space-info-pane.php');

Wordpress codex 页面上的这条评论让我到了那里:https://developer.wordpress.org/reference/functions/plugin_dir_path/#comment-2085

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 2013-03-18
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多