简体   繁体   English

为什么前端的wp-ajax返回0,但是在admin中它可以正常工作?

[英]Why wp-ajax in front end it return 0 but in the admin it works correctly?

These are the functions I used them in plugin. 这些是我在插件中使用的功能。 It works in backend but in frontend it respons 0 . 它在后端工作,但在前端响应0 I copy past the same code and also prefer admin_enqueue_scripts with wp_enqueue_scripts . 我复制了相同的代码,并且还喜欢使用admin_enqueue_scriptswp_enqueue_scripts

add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );

function my_action_callback() {
global $wpdb;
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
    echo $whatever;
wp_die();
}

function testajax(){
var data = {
    'action': 'my_action',
    'whatever': ajax_object.we_value      // We pass php values differently!
};

jQuery.post(ajax_object.ajax_url, data, function(response) {
    alert('Got this from the server: ' + response);
});
};

I used it by onClick event. 我通过onClick事件使用它。

I used also 我也用过

add_action( 'admin_enqueue_scripts', 'my_enqueue' );

for admin and 对于管理员和

add_action( 'wp_enqueue_scripts', 'my_enqueue' );

for frontend 用于前端

add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {

wp_enqueue_script( 'ajax-script',    get_stylesheet_directory_uri().'/my_query.js', array('jquery') );


  wp_localize_script( 'ajax-script', 'ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );   
}

This is the script I want to be loaded in my custom page just in custom page but it doesn't load in custom page. 这是我想仅在自定义页面中加载到我的自定义页面中的脚本,但不加载到自定义页面中。 For loading I must use it in functions.php, then when I use it in functions.php, it will be loaded in all pages as it says in comments. 为了加载,我必须在functions.php中使用它,然后在functions.php中使用它时,它将按照注释中的说明加载到所有页面中。 There is the problem. 有问题。

Is it possible that the URL you're trying to call doesn't exist in the Admin? 您尝试调用的URL是否可能在Admin中不存在? Try using ajaxurl instead of ajax_object.ajax_url 尝试使用ajaxurl而不是ajax_object.ajax_url

Ajax URL isn't available on front-end by default. 默认情况下,前端不提供Ajax URL。 You must localize it before using: 您必须先本地化它,然后再使用:

wp_localize_script('my_enqueue', 'ajax_object', array('ajax_url' => admin_url('wp-ajax.php')));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM