【问题标题】:how to get result of a function as string with ajax in wordpress如何在wordpress中使用ajax将函数的结果作为字符串获取
【发布时间】:2021-04-13 13:24:23
【问题描述】:

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

function ajax_say_hello(){
    return "hello";
}

我想将 ajax_say_hello() 的结果作为带有 ajax 的字符串。类似“你好”。
为此,我添加了以下内容:
在我的插件 function.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 定义正确。
但我得到了整个页面,控制台没有错误。这里出了什么问题,我该怎么办?

【问题讨论】:

    标签: php jquery ajax wordpress


    【解决方案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;
    }
    

    【讨论】:

    • tnx.没有区别,我的结果和以前一样。与我的代码相比,您的代码已经死了。
    • 不,我的代码不同。您的回拨ajax_say_hello 功能不正确。应该是ajax_post_ajax_say_hello
    • 我测试了我的代码并且工作正常。
    • 对不起,我改变了它,但我得到了相同的结果。我已经更新了帖子。
    • 可以分享页面链接吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 1970-01-01
    • 2012-05-11
    • 2022-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多