问题描述:

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?

网友答案:

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

网友答案:

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"];

相关阅读:
Top