How to do equivalent in JavaScript?

How to do equivalent in JavaScript?
0.0 0


How can I write the equivalent of an AJAX request in jQuery, specifically this-

            url: 'someUrl',
            type: 'GET',
            success: function(data) {

in plain JavaScript (using XMLHttpRequest)


Ew. Don’t. Use fetch instead as it will be replacing the XHR dance as the new standard.

.then(function(response) {
    if(response.ok) { //only send data to the success handler if it's got a status of 2XX
        return response.json();
    } else {
        throw { message: "ERROR!1!", data: response }; //there are many ways to do this
}).then(function(data) {
    //success is handled in the 'then' method's first parameter
}, function(error) {
    //thrown errors (404, 500, etc) are handled in the 'then' method's second parameter
}).catch(function(error) {
    //the 'catch' method handles network errors, but not server errors
    //example: if 'fetch' were not able to send a request, this would be invoked
    //however, if you get a 404, 500, or some other error response, it would be handled above


Wow, this is undoubtedly easier than XHR! Is this ES7 syntax? I’ve never seen this before.


Nope! That’s just the promise API. Otherwise, that’s all good ol’ fashioned ES5.


If you want to use jquery you can do so like this:

$.get ("").done (function (data){ ...});

You can also use it with promises:

$.get ("").then (function(data){ ...});

You can chain those “then” function together as well.