从jquery函数获取返回值

时间:2014-03-12 13:09:41

标签: javascript jquery

我有以下代码,这里我需要从getTime获取时间变量?

    function getTime(handleData) {
            return $.ajax({
          url: 'data',
        success:function(data) {
           handleData(data); 
              }
            });
           }


   getTime(function(output){

     if(output == null || output == undefined)
     console.log("data is null");
     arr1 = output.split('\n');

       var time= arr1[0];
      return time
      });

如果我试图将时间值设置为低于给定的未定义

 var time =getTime(function(output){

 if(output == null || output == undefined)
 console.log("data is null");
 arr1 = output.split('\n');

   var time= arr1[0];
  return time
  });

1 个答案:

答案 0 :(得分:1)

您正在返回$ .ajax调用的回调函数,而不是主getTime函数,因此您将始终未定义。要从函数中正确返回并在之后使用该值,您应该使用回调函数来完成工作,或使用async:false进行同步调用。

var timeVal;
function getTime() {
    $.ajax({
       url: 'data',
       async: false,
       success:function(data) {
           timeVal = data; 
       }
    });
}


getTime();
output = timeVal;
if(output == null || output == undefined)
     console.log("data is null");
arr1 = output.split('\n');
var time= arr1[0];
相关问题