提问者:小点点

如何在wordpress中用ajax将函数结果作为字符串


我正在为wordpress开发一个插件,我想在其中使用ajax。假设我有以下函数:

function ajax_say_hello(){
    return "hello";
}

我想用Ajax将ajax_say_hello()的结果作为字符串获得。类似于“hello”。
为此,我添加了以下内容:
在我的插件函数中。php>

add_action('wp_ajax_ajax_say_hello', 'ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_say_hello' );

在我的ajax.js>

jQuery(document).ready(function($) {
    $('#myform').on('submit', function(e) {
          var data = {
              action: 'ajax_say_hello',
          };

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

并且正确定义了ajaxurl。
但我得到的结果是整个页面在控制台中没有错误。这里出了什么问题,该怎么办?


共1个答案

匿名用户

试试下面的代码。

add_action('wp_ajax_ajax_say_hello', 'ajax_post_ajax_say_hello');
add_action( 'wp_ajax_nopriv_ajax_say_hello', 'ajax_post_ajax_say_hello' );
function ajax_post_ajax_say_hello(){
    echo "hello";
    die;
}