2015-10-15 247 views
0

为什么在函数被调用时不会返回一个值?我用回调试了一下,我似乎也无法让它工作。它让我console.log,但它不会将它返回到tmp变量。ajax函数的返回值

var URL = "https://api.instagram.com/v1/media/popular?client_id=642176ece1e7445e99244cec26f4de1f"; 

function getData(){ 
    var tmp; 
    $.ajax({ 
     type: "GET", 
     url: URL, 
     dataType: "jsonp", 
     success: function(result){ 
      if(result.meta.code == 200){ 
      tmp = result.data; 
      //console.log(result.data); 
      }else{ 
      alert('fail'); 
      alert(result.meta.error_message); 
      } 
     } 
    }); 
    return tmp; 
} 
console.log(getData()); // undefined? 

在此先感谢!

+0

为了使它工作,请添加prop'async:false',但我不会推荐它。 – DinoMyte

+1

如果您设置** async:false **,则脚本将阻塞,直到请求完成。这可能会影响用户界面中的用户体验。 –

+1

*请勿*添加prop'async:false',由于某种原因已弃用。学习如何使用异步操作代替 – DelightedD0D

回答

0

,我建议你在jQuery的

"use strict"; 

var URL = "https://api.instagram.com/v1/media/popular?client_id=642176ece1e7445e99244cec26f4de1f"; 

$.ajax({ 
    type: "GET", 
    url: URL, 
    dataType: "jsonp", 
    success: onInstagramSuccess, 
    error: onInstagramError 
}); 

function onInstagramSuccess(result){ 
    if(result.meta.code == 200){ 
     console.log(result.data); 
    } 
} 

function onInstagramError(result){ 
    if(result.meta.code == 404){ 
     alert('fail'); 
     alert(result.meta.error_message); 
    } 
} 

基本上阿贾克斯在Javascript以下使用Ajax的方法是异步的。在实际收到请求的结果之前,它不会调用成功或失败方法。

+0

对不起,我的问题是更多为什么它返回undefined?当它返回而不是console.log?感谢https://jsbin.com/rotuqoceki/edit?js,console – user3224271

+0

我已经在代码下面回答了它。 – Jason