【问题标题】:Trying to get access to admin-ajax.php but failing尝试访问 admin-ajax.php 但失败
【发布时间】:2020-06-29 16:07:35
【问题描述】:

我在通过 admin_url 访问 admin-ajax.php 时遇到了一些问题,并且每次都收到 400 Bad Request。看过这个论坛的一些帖子,但仍然不明白为什么它不起作用。

我的 setup.php 看起来像这样:

add_action('wp_enqueue_scripts', function () {

wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
wp_enqueue_script('sage/ajax-pagination', asset_path('scripts/ajax-pagination.js'), ['jquery'], null, true);

wp_localize_script( 'sage/ajax-pagination', 'sage', array(
    'ajax_url' => admin_url( 'admin-ajax.php' )
));
if (is_single() && comments_open() && get_option('thread_comments')) {
    wp_enqueue_script('comment-reply');
}

}, 100);

然后我添加了一个 ajax.js 脚本,我将使用它,它看起来像这样:

$(document).on( 'click', '.nav-links a', function( event ) {
  event.preventDefault();
  $.ajax({
    url: window.sage.ajax_url,
    type: 'post',
    data: {
      action: 'ajax_pagination'
    },
    success: function( result ) {
      alert( result );
    }
  })
})

因此,每当我单击 .nav_link 时,我只会收到“加载资源失败:服务器从 localhost:3000/wp-admin/admin-ajax.php 响应状态为 400(错误请求)。

有人知道我做错了什么吗?提前致谢!

【问题讨论】:

标签: php jquery ajax wordpress roots-sage


【解决方案1】:

您收到 400(错误请求)的原因是因为您没有在 ajax 调用中添加“nonce”。

当控制台显示“加载资源失败:服务器从 localhost:3000/wp-admin/admin-ajax.php 响应状态为 400(错误请求)。”这意味着它无法从服务器取回结果。您缺少对 ajax 请求非常必要的随机数。了解更多here

您的代码应如下所示。

wp_localize_script( 'sage/ajax-pagination', 'sage', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce' => wp_create_nonce('ajax-nonce')
));

在你的 JS 文件中。

$(document).on( 'click', '.nav-links a', function( event ) {
  event.preventDefault();
  $.ajax({
    url: window.sage.ajax_url,
    type: 'post',
    data: {
      action: 'ajax_pagination',
      nonce: window.sage.nonce,
    },
    success: function( result ) {
      alert( result );
    }
  })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-07
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多