1

javascript help: i have a php page that echos

['A', 28.006660938911], ['B', 71.993339061089]

now i need this converted into an array in javascript, but in ajax, "var myData = new Array($http.responseText);" does not work

2
  • JSON is your friend: how can json_encode be used here? (Make sure to use the correct flags! :-) Also, this has been asked on SO like a bazillion times... on the JavaScript side use the appropriate JSON decoding, of course. There is no such Array constructor that takes a string. It just doesn't work like that. Commented Oct 25, 2011 at 5:37
  • I second what Pst said. JSON will undoubtedly be the easiest (and probably most efficient) way to accomplish this. Commented Oct 25, 2011 at 5:43

2 Answers 2

3

If given string is:

var s = "['A', 28.006660938911], ['B', 71.993339061089]";
  1. try evaluating it (if you have no access to the PHP code you are using):

    var array = eval("[" + s + "]");
    
  2. try changing the response to JSON format (if you HAVE access to that PHP code):

    echo json_encode(array(array('A', 28.006660938911), array('B', 71.993339061089)));
    
  3. if i am wrong and you are given with two different arrays, try splitting the string first

0
0
var myJSONObject = <?php echo json_encode($someArray); ?>
alert(  myJSONObject.keyInTheArray  )

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.