json in flashvars
I want to use josn in my flashvars and I'm having trouble
here is my json
var flashvars = {
xmlFile: '<?php echo $preface.$xmlpath; ?>',
preface: '<?php echo $preface; ?>',
"preload": {
"url": "flash/someflash.swf",
"x": "375",
"y": "237"
}
};
here is what I have been trying
var jsondata:String = this.loaderInfo.parameters.preload;
if(jsondata){
//var jsonData:O开发者_如何转开发bject = JSON.decode(jsondata.toString()) ;
error_txt.text = jsondata.toString();
}
error_txt returns "object Object" but I can't access any part of the json object
I believe what is happening here is that Javascript calls .toString() on your flashvars variable and passes the resulting string to flash. If my hunch is correct you will need to pass the JSON as a string such as this.
var flashvars = "{xmlFile:'myFile.xml',
preface:'Preface',
{
'url': 'flash/someflash.swf',
'x': '375',
'y': '237'
}
}";
Flashvars are passed as a collection of name/value pairs, with the same format as GET or POST (url-encoded) parameters. So for both the name and the value you need the content to be a string, properly escaped. Other than hardcoding the JSON string, which is a bit error prone, you could write your data in a php assoc array, then encode it to JSON and then url encode it. The resulting string is what you will pass as the value.
Something like this (I haven't actually tested this snippet!)
<?php
$preload_data = array(
"url" => "flash/someflash.swf",
"x" => "375",
"y" => "237"
);
$preload_flashvar = rawurlencode(json_encode($preload_data));
?>
var flashvars = {
xmlFile: '<?php echo $preface.$xmlpath; ?>',
preface: '<?php echo $preface; ?>',
preload: '<?php echo $preload_flashvar; ?>'
};
PS
On second thoughts, it's quite likely that the SWFObject (which you seem to be using to embed the swf) does the url escaping for you (via encodeURIComponent or some home made function); I don't remember if that's the case, but if it is, you don't have to call rawurlencode
in your php code, as your data will get urlencoded twice. I can't test this right now, but give it a try with and without url-encoding in php; one of the two should work fine.
Where do you actually use/need JSON?...
var flashvars = {
xmlFile: '<?php echo $preface.$xmlpath; ?>',
preface: '<?php echo $preface; ?>',
preload: {
url: "flash/someflash.swf",
x: "375",
y: "237"
}
};
//in AS3
var params:Object = this.loaderInfo.parameters;
if(params != null)
{
var preload:Object = params.preload;
for( var name:String in preload )
trace( preload[name] );
}
精彩评论