Issue with JSON and jQuery Iteration
I'm pretty sure it's an obvious error somewhere on this - but let me explain what I'm donig :
I'm calling a PHP file via jQuery as follows :
$.getJSON("/phpincs/getbucket.php?awskey="+awskey+"&awssecret="+awssecret+"&bucket="+bucket,
function(json){
$.each(json,function(i,item){
$(new Option(item.name,item.name)).appendTo('#bucket_contents_0');
});
}
and the JSON file it returns is as follows :
Array
(
[bt_shop.png] => Array
(
[name] => bt_shop.png
[time] => 1260393948
[size] => 156985
[hash] => 8a4eba621d5e08b84c962a0ad21ec2ae
)
[开发者_运维问答me_profile.jpg] => Array
(
[name] => me_profile.jpg
[time] => 1260393952
[size] => 2714
[hash] => 4f5d185b0c671e6165902762681f098b
)
[thumbnail.aspx.jpeg] => Array
(
[name] => thumbnail.aspx.jpeg
[time] => 1260393951
[size] => 5268
[hash] => 6939efa58ff7ffcac17218ffdd0d5d8c
)
)
true
for some reason it doesn't seem to fire the function(json){} - I've stuck an alert(''); in and it doesn't do anything.
Can someone quickly explain to me what seems to be going wrong there?
Cheers,
Carl
It is more than likely not calling the callback function because it doesn't look like what you are returning is json. If you have an $variable defined that contains your array...call
echo json_encode($jsondata); exit;
At the end of your script.
I've changed the names of the inner arrays as your previous labels are going to cause problems with the dot. You will get an error like:
myArray.bt_shop is undefined
when you try to call
alert(myArray.bt_shop.png.name);
the only way it could be called is with
alert(myArray["bt_shop.png"].name);
So having changed your code a bit, this is the JSON version of your arrays...
{
"one":
{
"name": "bt_shop.png",
"time": "1260393948",
"size": "156985",
"hash": "8a4eba621d5e08b84c962a0ad21ec2ae"
},
"two":
{
"name": "me_profile.jpg",
"time": "1260393952",
"size": "2714",
"hash": "4f5d185b0c671e6165902762681f098b"
},
"three":
{
"name": "thumbnail.aspx.jpeg",
"time": "1260393951",
"size": "5268",
"hash": "6939efa58ff7ffcac17218ffdd0d5d8c"
}
}
Then you reference your fields like this when you have the object:
myArray["two"]["name"]
myArray["two"].name
myArray.two.name
Your returned file isn't JSON. Unless you're using PHP syntax to describe your JSON object for us, you need to encode it into JSON format using json_encode
.
What you call the JSON file isn't JSON. Or maybe do you use some PHP library that converts that strange format into JSON ?
精彩评论