Javascript: Building an array with a variable
Is it possible to take the contents of a variable and s开发者_如何学Gotick it into an array like so (I've tried to no avail):
First I get these values from a database and using php form into a hidden input:
{value: '1', name: 'name1'},{value: '2', name: 'name2'}
Then collect with javascript
document.getElementById("myelement").value
Then put the value
var meval = document.getElementById("myelement").value;
And then I try to build the data like so:
var data = {items: [meval]};
If I do this
var data = {items: [{value: '1', name: 'name1'},{value: '2', name: 'name2'}]};
it works but not the initial way with the variable. And I have to build the original data like that.
eval()
is evil! Use JSON.parse()
instead.
var data = {items: JSON.parse('['+meval+']')};
If you have jQuery included on your website, you can do $.parseJSON()
which works better on older browsers.
If your using a string, you can use eval() - but it's a bit naughty, as it introduces security & flow problems.
var meval = "[{value: '1', name: 'name1'},{value: '2', name: 'name2'}]";
var data = eval(meval);
Eric is right, you're generally better off using JSON than arbitrary JavaScript literals. Currently your literal isn't valid JSON because it's not using double-quoted property names and string values. Use json_encode
to get a JSON-compatible literal syntax.
You can fall back to eval()
as in other answers when JSON.parse
isn't available, but you will need to use extra brackets to ensure that eval
knows that the leading {
means an object literal and not a statement.
<?php
function js($s) { // shortcut to save some typing
echo json_encode($s, JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_QUOT|JSON_HEX_APOS);
}
$data= array(name=>$row['name'], value=>$row['value']);
?>
<input type="hidden" id="data" value="<?php js($data); ?>"/>
<script type="text/javascript">
var json= document.getElementById('data').value;
var data= 'JSON' in window? JSON.parse(json) : eval('('+json+')');
</script>
Actually the JSON_HEX
options in the js
function allow literals to be output in a way that is equally valid in an HTML attribute or a <script>
block, so you can indeed omit the hidden input and just say:
<script type="text/javascript">
var data= <?php js($data); ?>;
</script>
You need to eval that variable to turn it's content into the data structure:
var data = {items: [eval(meval)]};
Put the items into a hidden input in this format:
"name1"."|"."name2"."|"."name3"... and so on
Then in JS:
var list = document.getElementById("yourelement").value;
var arrayOfStuff = list.split("|");
Now your JS array looks like this:
array() {
[0] => "Name1"
[1] => "Name2"
[2] => "Name3"
... and so on
}
精彩评论