Can't get a global variable on http request function

时间:2017-06-09 12:42:41

标签: javascript variables scope

it should be an easy one but I am stuck. I would like to return the result of a function as a global variable. Here I have my function clearbit() for which I created the global variable clearbit_role.

But I can't alert this variable outside of the function... Any clue anyone? Thanks!

EDIT: Added a fiddle here: 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)

Thanks!

2 个答案:

答案 0 :(得分:0)

why don't you create the variable clearbit_role outside of the function

 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)

答案 1 :(得分:0)

The problem

is NOT in scoping, the clearbit_role variable is already a global variable. But the problem is clearbit function is take a time to make the http request.

so the alert function run before the clearbit_role variable declaration.

Solution

use a function to run after AJAX request done.

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)
}