【问题标题】:return value from function with post [duplicate]从带有帖子的函数返回值[重复]
【发布时间】:2013-11-27 04:47:16
【问题描述】:

我有功能:

function test(){
   $.post('data.php', function(val){
       return val;
   })

   return 'error';
}

我只是简单地使用它:

console.log(test());

post 正在执行 - 返回良好的值,但函数测试返回“错误”而不是 data.php 中的值。 是否有可能从 $.post 获得价值?如果是,怎么做?

【问题讨论】:

  • @reikyoushin 不。将返回undefined

标签: javascript php jquery


【解决方案1】:

return 语句不会将函数冒泡到全局范围内,如果您仔细观察,您会发现 return val 存在于它自己的函数中。

除此之外,该函数不是同步执行的,所以它在执行之前永远没有机会返回。

因此,您需要传入回调或使用 Promise 模式。谷歌搜索这些词会发现你对这两个词的丰富信息。

【讨论】:

    【解决方案2】:

    因为 post 是异步的,所以函数在 post 完成之前返回 'error'。尝试使用回调。像这样的:

    function test(callback) {
        $.post('data.php', function(val){
            callback(val);
        })
        .fail(function() {
            callback('error');
        });
    }
    
    function log(message) {
        console.log(message);
    }
    
    test(log);
    

    【讨论】:

      【解决方案3】:

      使用 Promise 处理错误。它会在 post 方法的回调之前调用您的代码返回“错误”。

      function test(){
         $.post('data.php', function(val){
             alert (val);
         }).fail(function(){ alert('error');});
      
      
      }
      

      【讨论】:

        【解决方案4】:

        试试这个

        function test(callback){
           $.post('data.php', function(val){
               if(typeof callback == 'function') callback(val);
           })
        }
        

        并调用

        test(function(val){ console.log(val) });
        

        【讨论】:

          猜你喜欢
          • 2021-07-02
          • 1970-01-01
          • 2016-09-10
          • 1970-01-01
          • 2015-05-25
          • 2012-08-14
          • 2020-08-26
          • 2011-04-18
          • 2011-04-19
          相关资源
          最近更新 更多