How can the value variable assign the resulting value that came in as a response from the web server?

var value; ... xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { //alert(xhr.responseText); var jsonResponse = JSON.parse(xhr.responseText); value = jsonResponse.id; //return value; } else { console.error(xhr.statusText); } //return value; }; ... 

Reported as a duplicate by the participants Grundy , cheops , Pavel Mayorov , aleksandr barakin , rjhdby 6 Oct '16 at 7:36 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • It is assigned easily, but it is unknown when. - Sergey Gornostaev
  • one
    if I understand correctly, then you try to use value before xhr.onreadystatechange occurs, most likely you need to call a function in the xhr.onreadystatechange body that contains the implementation of logic and pass value to it. Or specify the question. - Vyacheslav Danshin
  • @papiroca, I initially do not use value, but I want to transfer the resulting value to the function in the next step: chrome.runtime.sendMessage ({data: value}); - Forkildney65

1 answer 1

You already assign a parameter from the response to the variable value . But apparently you have a completely different question. You are making an asynchronous request, it looks most likely for you like this:

 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { //alert(xhr.responseText); var jsonResponse = JSON.parse(xhr.responseText); value = jsonResponse.id; } else { console.error(xhr.statusText); } }; xhr.open("GET",url, true); xhr.send(); 

The request is sent at the moment xhr.send () , and the function xhr.onreadystatechange will work when the answer comes. When this happens by and large is not known. To use the data from the response, you need to call an action in the callback function that should use the value variable, for example:

 var value; function useValue() { // Делаете то что вам нужно } xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { //alert(xhr.responseText); var jsonResponse = JSON.parse(xhr.responseText); value = jsonResponse.id; useValue(); } else { console.error(xhr.statusText); } }; 
  • It has already reached me. Thank you all for your help! - Forkildney65
  • and it is better to be careful with the visibility zone and pass useValue (value) without var value; - Vyacheslav Danshin
  • Yes, of course, but the value variable can be used by the author and in other places. - Alexey Prokopenko
  • one
    What do you think, how many more times can you answer this question before you lose your temper? :) - Pavel Mayorov