Populating a Javascript pulldown with a PHP array
In my web site I have the following:
formvalues.php -accesses-> database
database -sends data开发者_Go百科 to be stored in-> formvalues.php
registrationform.php -accesses variables-> formvalues.php
registration form display values accordingly.
I have a piece of javascript code that creates me a basic pull down menu (For testing purposes).
var sel = document.createElement('select');
sel.name = 'staff' + s;
option1 = document.createElement('option');
option1.name = 'Non-medical Staff';
option1.value = 'Non-medical Staff';
option1.innerHTML = option1.value;
option2 = document.createElement('option');
option2.name = 'Nurse';
option2.value = 'Nurse';
option2.innerHTML = option2.value;
sel.appendChild(option1);
sel.appendChild(option2);
document.getElementById('staffarea').appendChild(sel);
I was wondering how do could pass a PHP array variable into the javascript and populate the pulldown instead of manual data.
Do I need to connect it with my formvalues.php file?
Thanks
Try writing JavaScript from within your php script. Something like this:
<script type="text/javascript">
var myArray = new Array();
<?php
$your_php_array = array();
// somehow you populate that array
foreach ($your_php_array as $key=>$value) {
echo sprintf("myArray.push(%s);", $value);
}
?>
// do stuff with that array in javascript
</script>
Of course, if your JavaScript is external, you will have to do a workaround. Such as declaring that JS array as a global variable (still, inside ), and then referencing it with your script.
$key=>$value is optional, in case you ever need the key name.
精彩评论