What is the vanilla JS version of Jquery's $.getJSON

前端 未结 4 1902
礼貌的吻别
礼貌的吻别 2021-02-05 13:07

I need to build a project to get into a JS bootcamp I am applying for. They tell me I may only use vanilla JS, specifically that frameworks and Jquery are not permitted. Up to

4条回答
  •  半阙折子戏
    2021-02-05 14:09

    Here is the Vanilla JS version for $.getJSON :

    var request = new XMLHttpRequest();
    request.open('GET', '/my/url', true);
    
    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        var data = JSON.parse(request.responseText);
      } else {
        // We reached our target server, but it returned an error
    
      }
    };
    
    request.onerror = function() {
      // There was a connection error of some sort
    };
    
    request.send();
    

    Ref: http://youmightnotneedjquery.com/

    For JSONP SO already has the answer here

    With $.getJSON you can load JSON-encoded data from the server using a GET HTTP request.

提交回复
热议问题