douhui9380 2015-04-18 23:57
浏览 160
已采纳

带有wp_localize_script的Wordpress前端Ajax错误:未定义ajaxurl

I'm trying to create markers on a map via ajax on a wp theme. After some struggle I found out that I can't use any php file to get data via ajax, I have to use the admin-ajax.php file.

Accordingly to many examples, this is my code

in 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
}

The js file is loaded and working, it does other stuff before the ajax call, where it stops for an error in this line:

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

But I always Have the same error:

Reference Error: frontendajax.ajaxurl is not defined

where is my error?

PS: I use get_stylesheet_directory_uri() because I am in a child theme.

  • 写回答

2条回答 默认 最新

  • dougeqiang1619 2015-04-19 01:09
    关注

    From wp_localize_script docs:

    IMPORTANT! wp_localize_script() MUST be called after the script it's being attached to has been registered using wp_register_script() or wp_enqueue_script().

    And the handle must be the same:

    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' )));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同