0

i use this javascript code for a API request to get a JSON.

function loadJSON(url) {
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType('application/json');
    xobj.open('GET', url, false);
    xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == '200') {
            // Required use of an anonymous callback as .open will NOT return a value but simply returns undefined in asynchronous mode
            returnval = JSON.parse(xobj.responseText);
        }
    };
    xobj.send(null);
    return returnval;
}

The code is in a mouse-click event. The full URL is generated with data from the mouse click. The code is only work with sync. I have tested the code with async, but with this the code don't work. xobj.open('GET', file, true, null, null);

With sync, the console write:

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

OK, hey! There a many Threads with this question, but i don't found a solution. I use pure JavaScript, no Ajax, no JQuery.

daedsidog
  • 1,732
  • 2
  • 17
  • 36
pemente
  • 19
  • 3
  • 1
    _"The code is only work with sync."_: You should add the "mouse-click" code as there's probably a way to get the code to work asynchronously. – Andy Dec 23 '18 at 19:33
  • You should *never* block the main thread as it stops user interactivity. You should be using asynchrony. – Andrew Li Dec 23 '18 at 19:34
  • @Andy, there is a mouse-click-event with OpenLayers to get the coords, and the coords are writing in the request URL. – pemente Dec 23 '18 at 19:49
  • Consume the data in the `onreadystatechange` callback or return a promise that you resolve in `onreadystatechange` – charlietfl Dec 23 '18 at 19:52

1 Answers1

-2

You almost have it written asynchronously. Pass in a callback function to get your returnval.

function loadJSON(url, callback) {
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType('application/json');
  xobj.open('GET', url);
  xobj.onreadystatechange = function() {
    if (xobj.readyState == 4 && xobj.status == '200') {
      returnval = JSON.parse(xobj.responseText);
      callback(returnval);
    }
  };
  xobj.send(null);
}

loadJSON('https://jsonplaceholder.typicode.com/users', function(result) {
  console.log(result)
});
Will
  • 3,201
  • 1
  • 19
  • 17