【问题标题】:Wordpress Frontend Ajax with wp_localize_script Error: ajaxurl is not defined带有 wp_localize_script 错误的 Wordpress 前端 Ajax:未定义 ajaxurl
【发布时间】:2015-06-25 18:47:48
【问题描述】:

我正在尝试在 wp 主题上通过 ajax 在地图上创建标记。 经过一番挣扎,我发现我不能使用任何 php 文件通过 ajax 获取数据,我必须使用 admin-ajax.php 文件。

根据许多示例,这是我的代码

在functions.php中

add_action( 'wp_enqueue_scripts', 'add_frontend_ajax_javascript_file' );
function add_frontend_ajax_javascript_file()
{
   wp_localize_script( 'frontend_ajax', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    wp_enqueue_script( 'ajax_custom_script',  get_stylesheet_directory_uri() . '/includes/ajax-javascript.js', array('jquery') );

}

add_action( 'wp_ajax_get_post_information', 'get_post_information' );
add_action( 'wp_ajax_nopriv_get_post_information', 'get_post_information' );


function get_post_information() 
{ 

$get_this= $_GET['this'];
$get_that= $_GET['that'];

...my select...

echo json formatted data
}

js 文件已加载并正在工作,它在 ajax 调用之前执行其他操作,在此行中它会因错误而停止:

$.post({ 
        url:frontendajax.ajaxurl,
        {
            action: 'get_post_information',
            data: data
        },
        success: function(response) {

但我总是有同样的错误:

参考错误:未定义frontendajax.ajaxurl

我的错误在哪里?

PS:我使用 get_stylesheet_directory_uri() 因为我在子主题中。

【问题讨论】:

    标签: php jquery ajax wordpress frontend


    【解决方案1】:

    来自wp_localize_script docs

    重要! wp_localize_script() 必须在使用 wp_register_script() 或 wp_enqueue_script() 注册它所附加的脚本之后调用。

    并且句柄必须相同:

    wp_enqueue_script( 'ajax_custom_script',  get_stylesheet_directory_uri() . '/includes/ajax-javascript.js', array('jquery') );
    wp_localize_script( 'ajax_custom_script', 'frontendajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
    

    【讨论】:

    • 谢谢,我没有意识到我需要使用同一个句柄!为了使其工作,我还必须将操作函数的名称与数据一起传递(我更新了我的问题)
    • 脚本的位置是引起我问题的原因。这是正确的答案!
    • 必应!那完全是我的问题。我在函数中有 wp_enqueue_script() 和 wp_localize_script(),但是顺序错误。交换它们完全解决了我的问题。
    • 谢谢!我根本想不通
    【解决方案2】:

    我正在尝试在 wp 主题上通过 ajax 在地图上创建标记。经过一番挣扎,我发现我不能使用任何 php 文件通过 ajax 获取数据,我必须使用 admin-ajax.php 文件。

    admin_url('admin-ajax.php') )); }); ?>

    【讨论】:

    猜你喜欢
    • 2018-05-30
    • 1970-01-01
    • 2011-06-10
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多