猿问

无法在jQuery函数中返回$ .posted的php文件数据

这是我的自定义jQuery函数:


(function($){

    $.fn.NotYet = function(arti_id) {

        this.append(function() {

            var result = 0;

            $.post("comment_load.php", {arti_id:arti_id, status:1}, function(data){

                console.log(data);          // Returns data from POSTed PHP file

                console.log(result);        // Returns 0

                //$(this).append(result);   // Not Working

                result = data;

                console.log(result);        // Returns data from POSTed PHP file

            });

            console.log(result);            // Returns 0

            return result;                  // Returns 0

        });         

        return this;                        // Returns 0

    };

})(jQuery);

我正在这样调用函数:


$("div#Comments").NotYet(15);

我正在尝试制作jQuery函数,但无法将发布的php文件数据返回到<div>容器中。


有什么建议么?


繁华开满天机
浏览 124回答 1
1回答

守着一只汪

$.post&nbsp;是异步方法,它无法返回任何内容。而且您的问题是在ajax调用结束之前设置了结果值。这就是为什么console.log值设置为的原因0。因此,您需要在成功函数的回调中进行设置。并且在回调this元素内部为无效元素,因此您需要在传递给成功函数之前声明另一个变量,例如var that = this代码:(function($) {&nbsp; &nbsp; &nbsp; $.fn.NotYet = function(arti_id) {&nbsp; &nbsp; &nbsp; &nbsp; this.append(function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var that = this;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var result = 0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $.post("comment_load.php", {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; arti_id: arti_id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; status: 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }, function(data) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(data); // Returns data from POSTed PHP file&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $(that).append(data);&nbsp; &nbsp;//its work&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result = data;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log(result); // Returns 0 //its excute before ajax call&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return result; // its not possible&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; })(jQuery);
随时随地看视频慕课网APP
我要回答