0

I have a simple AJAX script to load a file into an array.

var loadGame = function() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      game = this.responseText
    }
  };
  xhttp.open('GET', 'games/' + $('.meta').html() + '.game', true);
  xhttp.send();
}

However, game is treated as a string, not an array, even if this.responseText is a valid array. How can I get JS to treat this.responseText as an array when I store it to game?

12
  • perhaps JSON.parse will help Commented Oct 23, 2016 at 23:51
  • Can you elaborate? I've seen something like this, but I'm really looking for a built in command to convert between types. Commented Oct 23, 2016 at 23:54
  • 2
    can I elaborate? Better than that, I can link to documentation ... built in command to convert between types - what does the received data look like ... exactly Commented Oct 23, 2016 at 23:56
  • The file contents: ['a','b'], and how AJAX import it: "['a','b']". Commented Oct 23, 2016 at 23:58
  • 1
    @T.Chmelevskij - so would ["a", "b"] - which is why I asked why you'd need to add extra complexity Commented Oct 24, 2016 at 0:06

2 Answers 2

1

because the file uses ' to delimit strings, JSON.parse wont work

the following may help depending on the data

game = JSON.parse(this.responseText.split("'").map(function(x) { return x.replace(/"/gm, "'"); }).join('"'));

If any values have ' or " in then, this wont work very well though

Another far simpler solution is using eval ...

eval("game=" + this.responseText);

Just be careful using eval

Sign up to request clarification or add additional context in comments.

Comments

0

xhttp.responseText is always a string. however, you can get it as an array using JSON.parse(xhttp.responseText). Before you can use JSON.parse, you should encode it in json in the server. in php, you can do it is json_encode function. like the following

    //php
  $response = array("a", "b", "c", "d");
  echo json_encode($response);

using JSON.parse in the client will return ["a", "b", "c", "d"];

2 Comments

Nice suggestion, but I am importing from a file already in array format.
so, simply use JSON.parse(xhttp.responseText) to get it in array format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.