2017-06-09 82 views
0

它應該是一個容易的但我卡住了。 我想返回一個函數的結果作爲一個全局變量。在這裏我有我的函數clearbit(),爲此我創建了全局變量clearbit_role。http請求函數無法獲得全局變量

但是我不能在函數之外提醒這個變量......任何線索都可以嗎? 謝謝!

編輯:這裏增加了一個小提琴: http://jsfiddle.net/luron01/sJ8Eu/9/

var clearbit_role ; 
function clearbit (web){ 
    var url = "https://prospector.clearbit.com/v1/people/search?domain=clearbit.com&seniorities[]=executive&seniorities[]=manager&limit=1"; 
    var request = new XMLHttpRequest(); 
    request.onreadystatechange = function() { 
    if (request.readyState === 4 && request.status == 200) { 
     var response = JSON.parse(request.responseText.replace('[','').replace(']','')); 
     var clearbit_fullname = response.name.fullName; 
     clearbit_role = response.role; 
     clearbit_role='test' 

    } 
    } 
    request.open('GET', url, true); 
    request.setRequestHeader("authorization", "Bearer sk_605e7e64cbb1ebcca9e28b8a97d23f22") 
    request.send(); 
} 
clearbit() 
alert(clearbit_role) 

謝謝!

+0

這是* *異步所以'警報(clearbit_role)'調用執行完畢之前。在'onreadystatechange'上做你的工作 –

+0

在clearbit_role = response.role後添加console.log(response.role);查看response.role是否未定義 –

+0

確實在onreadystatechange中有效,但我需要將clearbit_role返回到另一個函數。 – Ludo

回答

0

你爲什麼不創建變量clearbit_role功能

var clearbit_role ; 
    function clearbit (web){ 
    var url = "myurl"; 
    var request = new XMLHttpRequest(); 
    request.onreadystatechange = function() { 
    if (request.readyState === 4 && request.status == 200) { 
     var response = JSON.parse(request.responseText.replace('[','').replace(']','')); 
     var clearbit_fullname = response.name.fullName; 
     clearbit_role = response.role; 
    } 
    } 
    request.open('GET', url, true); 
    request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b") 
    request.send(); 
} 
clearbit() 

alert(clearbit_role) 
+0

然後它顯示爲「undefined」 – Ludo

+0

不,這不是問題。你不需要那樣做。作爲例子非常簡單的代碼https://jsfiddle.net/op92cf1o/ –

0

問題

之外沒有在劃定範圍,該clearbit_role變量已經是一個全局變量。但問題是clearbit函數需要一段時間才能發出http請求。

因此alert函數在clearbit_role變量聲明之前運行。

解決方案

使用一個函數來完成AJAX請求後運行。

function clearbit (web){ 
 
     var url = "myurl"; 
 
     var request = new XMLHttpRequest(); 
 
     request.onreadystatechange = function() { 
 
     if (request.readyState === 4 && request.status == 200) { 
 
      var response = JSON.parse(request.responseText.replace('[','').replace(']','')); 
 
      var clearbit_fullname = response.name.fullName; 
 
      clearbit_role = response.role; 
 
      someFunctionThatRunAfterAjaxDone(clearbit_role); 
 
     } 
 
     } 
 
     request.open('GET', url, true); 
 
     request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b") 
 
     request.send(); 
 
    } 
 
    clearbit() 
 
// But all code you want to fun after AJAX done inside this function 
 
function someFunctionThatRunAfterAjaxDone(clearbit_role) { 
 
    alert(clearbit_role) 
 
}