为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
繁华开满天机 2021-03-30 13:14:54
这是我的自定义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>容器中。有什么建议么?
查看完整描述

1 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

$.post 是异步方法,它无法返回任何内容。而且您的问题是在ajax调用结束之前设置了结果值。这就是为什么console.log值设置为的原因0

  1. 因此,您需要在成功函数的回调中进行设置。

  2. 并且在回调this元素内部为无效元素,因此您需要在传递给成功函数之前声明另一个变量,例如var that = this

代码

(function($) {

      $.fn.NotYet = function(arti_id) {

        this.append(function() {

         var that = this;

          var result = 0;

          $.post("comment_load.php", {

            arti_id: arti_id,

            status: 1

          }, function(data) {

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


            $(that).append(data);   //its work

            result = data;


          });

          console.log(result); // Returns 0 //its excute before ajax call

          return result; // its not possible

        });

      };

    })(jQuery);


查看完整回答
反对 回复 2021-04-23
  • 1 回答
  • 0 关注
  • 123 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信