【问题标题】:Data that's returning from function is undefined从函数返回的数据未定义
【发布时间】:2012-12-14 11:48:54
【问题描述】:

我在将数据从 ajax 返回到调用方函数时遇到问题。当我在 console.loging 时它是未定义的。

我相信我的问题是由于 js 是异步的,当我在 console.loging 数据时它还没有准备好。我能做些什么来解决它?

FooFunction: function(userInput){

    var fooData = FooFunction2(userInput);
    console.log(fooData);     // <--- undefined
},

FooFunction2: function(userInput) {

    $.ajax({
         url:'./php/test.php',
         type:'post',
         dataType:'json',
         data:{ 
             fooData: userInput
         },
         success:function(data) {
             ...manipulating the data...

             console.log(manipulatedData);    // <--- ['foo', 'foo2'];
             return manipulatedData;
         }
    });
},

【问题讨论】:

  • 请显示console.log(data); 显示的内容。
  • 从哪里来,在哪里定义 userInput ??你对这个例子什么都没说,你应该检查那个 var 开始的地方

标签: javascript jquery ajax asynchronous return


【解决方案1】:

ajax 调用是异步的,所以返回不起作用。更改您的代码以使用在 ajax 调用完成时调用的回调。

我改变了你的代码来做到这一点:

FooFunction: function(userInput){
    var callbackfunc = function(ajaxData)
    {
        console.log(ajaxData); //ajax is complete!
    };

    this.FooFunction2(userInput, callbackfunc);
},

FooFunction2: function(userInput, callbackfunc) {

    $.ajax({
         url:'./php/test.php',
         type:'post',
         dataType:'json',
         data:{ 
             fooData: userInput
         },
         success:function(data) {
             ...manipulating the data...

             console.log(manipulatedData);    // <--- ['foo', 'foo2'];
             callbackfunc(manipulatedData);
         }
    });
},

【讨论】:

    【解决方案2】:

    FooFunction2 是对象使用的属性this.FooFunction2

    你不能从异步方法返回。使 ajax 调用同步或 proivde 回调。

    FooFunction: function(userInput){
    
        var fooData = this.FooFunction2(userInput);
        console.log(fooData);     // <--- undefined
    },
    

    修改后的代码

    FooFunction: function(userInput){
    
         this.FooFunction2(userInput, function(fooData){
              console.log(fooData);     // <--- undefined
        });
    
    },
    
    FooFunction2: function(userInput, cb) {
    
        $.ajax({
             url:'./php/test.php',
             type:'post',
             dataType:'json',
             data:{ 
                 fooData: userInput
             },
             success:function(data) {
                 ...manipulating the data...
    
                 console.log(manipulatedData);    // <--- ['foo', 'foo2'];
                 cb(manipulatedData);
             }
        });
    },
    

    【讨论】:

    • @undefined:是的,确实如此。解决无法从异步函数返回的方法是改用回调。
    猜你喜欢
    • 1970-01-01
    • 2012-01-15
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多