【问题标题】:Wordpress admin-ajax.php returns 0 even if using wp_die()即使使用 wp_die(),Wordpress admin-ajax.php 也会返回 0
【发布时间】:2021-06-13 11:23:59
【问题描述】:

我正在尝试使用简单的 ajax 调用来过滤我的帖子,但由于我的 admin-ajax.php 调用总是返回 0,所以无法让它工作。 这个问题有很多问题,但它们大多是通过添加 wp_die() 来解决的, 这并没有解决我的问题。

Ajax 调用:

$.ajax({
  type: 'POST',
  url: '/wp-admin/admin-ajax.php',
  dataType: 'html',
  data: {
    action: 'filter_projects',
  },
  success: function(res) {
    $('.project-tiles').html(res);
    console.log(res);
} 
})

PHP函数:

function filter_projects() {
  echo "<p>test</p>";
  wp_die();
}
add_action('wp_ajax_filter_projects', 'filter_projects');
add_action('wp_ajax_nopriv_filter_projects', 'filter_projects');

PHP 函数注册正确,因为我得到了 200,但它总是返回 0 和“成功”。

我已经尝试过的:

  • WP_DEBUG=1 --> 没有错误
  • 检查开发控制台 --> 没有错误
  • 检查网络 --> admin-ajax.php 调用时为 200,但收到“0”
  • 尝试 die() 并退出而不是 wp_die()

我不知道如何进一步调试它,因为它没有返回任何错误。

有人有想法吗?

【问题讨论】:

  • 请分享更多细节。您尝试过什么来解决问题?你被困在哪里了?为什么不正确调试问题?

标签: php jquery ajax wordpress


【解决方案1】:

不要直接回显您的 HTML,而是尝试使用 JSON 处理结果,这样您就可以获得更好的结果来评估您的测试。 我将如何进行您发布的相同测试(使用直接 JS 而不是 JQUERY):

                  let xhr = new XMLHttpRequest();
                   
                  xhr.open('POST', "/wp-admin/admin-ajax.php", true);

                  xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

                  var params = 'action=filter_projects';
                  
                  xhr.onreadystatechange = () => {

                    if(xhr.readyState == 4) {

                      // RETURN OK
                      if(xhr.status == 200) {

                         console.log(xhr.responseText); // TEXT RESPONSE
                         console.log(JSON.parse(xhr.responseText));  // JSON RESPONSE
                         
                      // HTTP ERROR 
                      }else{
                        
                        console.log("SOME ERROR HTTP");
                        console.log(xhr.responseText);

                      }

                    }
                }; 

                xhr.send(params);

PHP 代码:

function filter_projects() {

$content = "test";

$data = array('success' => "200", 'content' => $content);

$json_string = json_encode($data, JSON_PRETTY_PRINT);

echo $json_string; 

wp_die();

}

add_action('wp_ajax_filter_projects', 'filter_projects');
add_action( 'wp_ajax_nopriv_filter_projects', 'filter_projects' );

【讨论】:

  • 请分享更多细节 - 是什么让您认为这段代码更好用?如果当前代码总是从后端调用返回0,那么更改任何 JS 部分都不会改变
猜你喜欢
  • 2016-12-17
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-07
相关资源
最近更新 更多