变量 PHP 返回 ajax 中的未定义(发送回未定义到 ajax)


variable php return undefined in ajax (send back undefined to ajax)

实际上,我正在寻找问题的解决方案,但我无法解决这个问题。在此 Ajax 中,返回警报中的undefined

PHP函数:

function myfunc(){
    $arr = array(
        'var' => 'hello',
    );
    echo json_encode($arr);
}
add_action('wp_ajax_myfunc', 'myfunc');
add_action('wp_ajax_nopriv_myfunc', 'myfunc');

和 jQuery:

<script type="text/javascript">
    $(function(){
        $.ajax({
            type: 'POST',
            url: "<?php echo admin_url("admin-ajax.php"); ?>",
            dataType: 'json',
                data: {
                    action : 'myfunc',
                },
                success: function(data,textStatus) {
                    alert(data.var);
                }
        });
    });
</script>

另外,我尝试了alert(data);,但它返回 0。

问题解决了。问题是功能的最后一行中缺少"退出"。谢谢。。

最佳做法是使用 wp_die() 而不是 exit()。 请参阅:https://codex.wordpress.org/AJAX_in_Plugins