1

is there anyway to import a javaScript array from a PHP return value?

Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.

$.get(makeArray.php, function(data){
    var responseArray = new Array(data);
    alert(responseArray[1]);
    ...

However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.

Thanks!

4

2 回答 2

3

You can use JSON.

In PHP

$myarray = array('first','second','third');
return json_encode($myarray);

In JavaScript:

$.get(makeArray.php, function(data){
  console.log(data[1]); //=> "second"
}, 'json');

Edit

If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:

PHP:

echo join('%',$myarray);

JS:

var array = data.split('%');
于 2013-05-07T11:15:01.257 回答
0

Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.

What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.

于 2013-05-07T11:16:54.987 回答