Reputation: 21
I have an array in php file test.php; I need it in Javascript array.
<?php
$phpArray = glob('*.jpg');
echo json_encode($phpArray);
?>
I need each filename in Javascript array so I can access it like:
myJavasciptArray[0];
I need to get my JavaScript array loaded from the function:
$("#button2").click(function(){
$.get("test.php",function(data){
var mypics=data;
alert(mypics[1]);
});
});
but what I get instead of each filename in the array is a character.
myJavasciptArray[0]="["
instead of:
myJavasciptArray[0]="myfile1.jpg"
Upvotes: 2
Views: 46
Reputation: 3665
What you getting is a string back from the request, you will need to use JSON.parse() function to get the correct json object
var mypics = JSON.parse(data)
Upvotes: 0
Reputation: 23255
instead of using jQuery.get()
, use jQuery.getJson()
and you should be fine. If you don't, myJavascriptArray
is a string, and someString[0]
means the first letter of the string.
Upvotes: 1
Reputation: 5323
Try JSON.parse here :
$.get("test.php",function(data){
var mypics = JSON.parse(data);
alert(mypics[1]);
});
Upvotes: 0
Reputation: 2459
You are not getting result as JSON type.
Add json
dataType to your $.get()
so result is parsed as JSON:
$("#button2").click(function(){
$.get("test.php",function(data){
var mypics=data;
alert(mypics[1]);
}, 'json');
});
Upvotes: 0