为什么AJAX json脚本返回额外的0(零)

Jas*_*son 4 javascript ajax jquery json jsonp

我在WordPress中有一个AJAX函数,它调用PHP函数来返回数据库中瞬态记录的值.

当我使用jQuery调用函数时,我收到结果,但它总是在值上附加一个额外的0(零).

这是我的jQuery函数:

(function($) {
    $(document).ready( function() {

        var AdvancedDashboardWidget = function(element, options)
        {
            var ele = $(element);
            var settings = $.extend({
                action: '',
                service: '',
                countof: '',
                query:   '',
                callback:''
            }, options || {});
            this.count=0;
            var url='';
            switch(settings.service)
            {
                case 'facebook':
                    if(settings.countof=='likes' || settings.countof=='talks')
                    {
                        ajaxCall(action,ele,settings);  
                    }
            }
        };

    var ajaxCall = function(action,ele,settings){
        opts = {
            url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php
            type: 'POST',
            async: true,
            cache: false,
            dataType: 'json',
            data:{
                action: settings.action // Tell WordPress how to handle this ajax request
            },
            success:function(response) {
                //alert(response);
                ele.html(response);
                return; 
            },
            error: function(xhr,textStatus,e) {  // This can be expanded to provide more information
                alert(e);
                //alert('There was an error');
                return; 
            }
        };
        $.ajax(opts);
    };


        $.fn.advanceddashboardwidget = function(options)
        {
            return this.each(function()
            {
                var element = $(this);

                // Return early if this element already has a plugin instance
                if (element.data('advanceddashboardwidget')) return;

                // pass options to plugin constructor
                var advanceddashboardwidget = new AdvancedDashboardWidget(this, options);

                // Store plugin object in this element's data
                element.data('advanceddashboardwidget', advanceddashboardwidget);
            });
        };

    });
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

还有更多辅助函数,但这是与WordPress通信并返回PHP函数值的主要jQuery函数.

问题是,如果值返回为" 99",例如它将返回为" 990"

这是jQuery调用的PHP函数:

/**
* Get Facebook Likes
*/

public function get_facebook_likes(){

    echo 99;
}
Run Code Online (Sandbox Code Playgroud)

如果我改变上面的内容return 99;我收到普通0

Lew*_*wis 6

您的函数应该使用wp_send_json将PHP编码为JSON并将其发送回AJAX请求处理程序.这也将停止执行任何后续PHP,因此不需要使用exit或die.

因此,对于您的具体示例,您将使用:

/**
* Get Facebook Likes
*/

public function get_facebook_likes(){
   wp_send_json(99);
}
Run Code Online (Sandbox Code Playgroud)