2015-04-18 36 views
0

我试图在地图上通过ajax在wp主题上创建标记。 经过一番斗争后,我发现我不能使用任何PHP文件通过ajax获取数据,我必须使用admin-ajax.php文件。Wordpress前端Ajax与wp_localize_script错误:ajaxurl没有定义

因此很多例子,这是我的代码

中的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(),因为我在一个儿童主题。

回答

3

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().

而且手柄必须是相同的:

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'))); 
+0

谢谢,我没有意识到我需要使用相同的句柄!为了使它工作,我还必须传递动作函数的名称以及数据(我更新了我的问题) – bluantinoo

0

我试图通过AJAX地图上的WP主题上创建标记。经过一番斗争,我发现我不能使用任何PHP文件通过ajax获取数据,我必须使用admin-ajax.php文件。

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

我真的建议你仔细阅读WP Ajax文档https://codex.wordpress.org/AJAX_in_Plugins 我知道它是有点混淆一见钟情,在这里你可以找到一个真实世界的例子https://www.sitepoint.com/how-to-use-ajax-in-wordpress-a-real-world-example/ – bluantinoo

相关问题