I have a PHP object like so:
Array (
[Apples] => stdClass Object (
[RandomText] => Apples
[RandomNumber1] => 30
[RandomNumber2] => 21
)
[Oranges] => stdClass Object (
[RandomText] => Oranges
[RandomNumber1] => 20
[RandomNumber2] => 45
) )
My ultimate goal is to be able to use this with jQuery. In particular, in a form select, once the option is changed to "Apples", it alerts "RandomString1 is greater than RandomString2", and when it's changed to Oranges, it alerts "RandomString1 is smaller than RandomString2" and so on with many more iterations.
My question is, how do I do this? I've tried adding this to my PHP:
echo '<script> var json = '. json_encode($myArray).'</script>';
which outputs:
var json = {"Apples":{"RandomText":"Apples","RandomNumber1":"30","RandomNumber2":21},"Oranges":{"RandomText":"Oranges","RandomNumber1":"20","RandomNumber2":45}}
But I cannot figure out how to proceed from here.
Any help, even poin开发者_如何学运维ting me where to look, would be greatly appreciated :)
You're almost there…
$('select').change(function(){
var fruit = $(this).val();
if (json[fruit].RandomNumber1 > json[fruit].RandomNumber2) {
alert(json[fruit].RandomText);
} else {
alert('Something else?');
}
});
You should probably use Inspector/Firebug to play with the JS console in your browser so you can try things out easily. You can start by just writing json;
and seeing what it returns. Then start playing with different ways of navigating the tree.
精彩评论