2015-10-15 121 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