0

my code like this

    var key,value;     
   //……some code……    
   function checkReg(i,j){    
       $.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){    
           alert(c.status);    
           return(c.status);    
       });      
   }        
    var temp=checkReg(key,value);    
    alert(temp);   

The problem is when I run it in my browser, it always fist alert undefined then alert the return value; seems like that can not get the return value of function checkReg. I was so confused, what should I do?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
wengcan
  • 31
  • 2
  • You will have to process the value from within `$.getJSON` is it is asynchronous. Your `return` is returning from `getJSON`'s callback function, not `checkReg` – tpbowden Apr 08 '13 at 10:24

2 Answers2

4

That's because your ajax call is running asynch from the rest. Your code will already have returned before before the ajax is even triggered.

So the returning doesn't work like that, you should provide a callback to your function instead of trying to return it.

function checkReg(i,j, callback){    
       $.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){    
           alert(c.status);    
           callback(c.status);    
       });      
   }        
    checkReg(key,value, function(temp){
          alert(temp);   
    }); 
fmsf
  • 36,317
  • 49
  • 147
  • 195
0

you cannot do that... since ajax is ashynchronus ... by the time the success function is called and return, the alert will be called thus having temp as undefined or empty.. one way to do this is doing the thing you need to inside the success called back of getJSON... or use $.deffered or callinga calback function..

function checkReg(i,j, callback){    
   $.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){    
       callback(c.status);    
   });      
}        
checkReg(key,value, function(temp){
      alert(temp);   
}); 
bipen
  • 36,319
  • 9
  • 49
  • 62