P
P
Pavel Chuev2015-10-04 11:16:34
JavaScript
Pavel Chuev, 2015-10-04 11:16:34

How to force the code to read the server's response?

This code doesn't work because, for reasons I don't understand, it doesn't read the server's response.

function RequestItems() {
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            data.forEach(function(e){
                var ubid = e.ui_bid;
                +ubid&&my_func(ubid);
            })
        }};
    xhr.open('GET', 'https://csgo.tm/api/Trades/?key=' + secretkey, false);
    xhr.send();
}

And if you change it a little, then:
function RequestItems() {
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            console.log(data);
        }};
    xhr.open('GET', 'https://csgo.tm/api/Trades/?key=' + secretkey, false);
    xhr.send();
}

in the console, I still get the server response.
How can I change the code so that the first version of the code iterates over the server response (array) and performs the actions I need with it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-10-04
@Deonisius

The response from the server comes to you as a string. If you need to pass an array / object, then you first need to convert it to a string, or more precisely, to a JSON format string. In PHP, the json_encode() function is responsible for this . Having received such a json string on the client, you need to do the reverse transformation, parse this string:
var data = JSON.parse(xhr.responseText);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question