L
L
liqute2018-11-15 22:53:50
JavaScript
liqute, 2018-11-15 22:53:50

How to include external JSON and access its keys?

There is an external JSON file on a third-party resource (API), I connect via AJAX, I don’t know how to access the JSON file to start working with it. Using only pure JS
I want to bind to it to get the keys and scatter to populate the HTML

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.randomuser.me/1.0/?results=50&nat=gb,us&inc=gender,name,location,email,phone,picture', true);
xhr.send(null);
if (xhr.status != 200) {
  alert( xhr.status + ': ' + xhr.statusText );
} else {
  alert( xhr.responseText ); 
 }

I have been looking for an answer for the second day, except for JQuery (.getJSON) I didn’t find anything understandable, I don’t need to write code, please point me in the right direction!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ihor Bratukh, 2018-11-16
@BRAGA96

I would do something like this:

request('http://api.randomuser.me/1.0/', {
    results: 50,
    nat: ['gb', 'us'],
    inc: ['gender', 'name', 'location', 'email', 'phone', 'picture']
}).get(function (data) {
    console.log(data);
}, function (error) {
    console.log(error);
});

request('https://jsonplaceholder.typicode.com/posts', {
    title: 'foo',
    body: 'bar',
    userId: 1
}).post(function (data) {
    console.log(data);
}, function (error) {
    console.log(error);
});

function request(link, params, setup) {
    return {
        get: function (success, error) {
            return ajax(extend({}, {
                url: link + (params ? '?' + param(params) : ''),
                method: 'GET',
                success: success || function () {},
                error: error || function () {}
            }, setup || {}));
        },
        post: function (success, error) {
            return ajax(extend({}, {
                url: link,
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json; charset=UTF-8'
                },
                data: params,
                success: success || function () {},
                error: error || function () {}
            }, setup || {}));
        }
    };
}

function ajax(params) {
    var setting = extend({}, {
        url: window.location.href,
        method: 'GET',
        async: true,
        data: undefined,
        headers: {
            'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        success: function (data, xhr, params) {},
        error: function (error, xhr, params) {}
    }, params || {});
    var setHeaders = function (headers) {
        for (var name in headers) {
            this.setRequestHeader(name, headers[name]);
        }
    };
    var xhr = new XMLHttpRequest();
    xhr.open(setting.method, setting.url, setting.async);
    setHeaders.call(xhr, setting.headers);
    xhr.onreadystatechange = function () {
        if (this.readyState === 4) {
            if (this.status >= 200 && this.status < 400) {
                var data = (function () {
                    try {
                        return JSON.parse(this.response); 
                    } catch (error) {
                        return this.response;
                    }
                }).call(this);
                setting.success(data, this, setting);
            } else {
                setting.error(this.status, this, setting);
            }
        }
    }
    xhr.send(setting.data ? JSON.stringify(setting.data) : null);
    return xhr;
}

function param(data) {
    var result = '';
    for (var name in data) {
        result += name + '=' + (Array.isArray(data[name]) ? data[name].join(',') : data[name]) + '&';
    }
    return result.slice(0, -1);
}

function extend(output) {
    output = output || {};
    for (var i = 1; i < arguments.length; i++) {
        if (!arguments[i]) continue;
        for (var key in arguments[i]) {
            if (arguments[i].hasOwnProperty(key)) {
                output[key] = arguments[i][key];
            }
        }
    }
    return output;
}

But in short, here it is:
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.randomuser.me/1.0/?results=50&nat=gb,us&inc=gender,name,location,email,phone,picture', true);
xhr.onreadystatechange = function () {
    if (this.readyState === 4) {
        if (this.status >= 200 && this.status < 400) {
            var data = JSON.parse(this.response);
            console.log('Успех', data);
        } else {
            console.log('Ошибка', this);
        }
    }
}
xhr.send(null);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question