Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What's more convenient

$.getJSON('/my/url', function(data) {

});

or

var request = new XMLHttpRequest(); request.open('GET', '/my/url', true);

request.onload = function() { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.response); } else { // We reached our target server, but it returned an error

  }
};

request.onerror = function() { // There was a connection error of some sort };

request.send();

?



To be fair with the comparison, we should add error handling for the jQuery example:

  $.getJSON('/my/url')
    .done(data => {
      // success
    })
    .fail((jqxhr, textStatus) => {
      if (textStatus === 'timeout') {
        // connection error
      } else {
        // HTTP status error
      }
    })
And also consider the Fetch API alternative:

  fetch('/my/url')
    .then(response => {
      if (!response.ok) {
        // HTTP status error
      }
      return response.json()
    })
    .then(data => {
      // success
    })
    .catch(error => {
      // connection error
    })


Why not use fetch?


fetch('/my/url').then(response => response.json()).then(data => handle it)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: