我在数组中使用PHP生成一个html select元素,如下所示
$countries = array(
array('iso' => 'AF', 'name' => 'Afghanistan', 'key' => 'Red'),
array('iso' => 'AX', 'name' => 'Åland Islands','key' => 'Yellow'),
array('iso' => 'AL', 'name' => 'Albania', 'key' => 'Blue')
);
$select = '<select id="country_select" onchange="countryfind()">';
foreach($countries as $country) {
$select .= '<option value="'.$country['key'].'">'.$country['name'].'</option>';
}
$select = '</select>';
return $select;
选择框使用小的javascript函数显示所选国家/地区的国家/地区密钥:
function countryfind(){
jQuery('#countrykey').text(
jQuery('#country_select option:selected').val()
)};
我现在想使用该密钥与另一个PHP数组接口,该数组包含有关该国家/地区的信息,并在#countrykey div中显示该国家/地区而不是所选的值:
$si_federations = array(
'Red' => array('name'=>'A Red Country', 'url'=>'http://www.redcountry.com'),
'Blue' => array('name'=>'A Blue Country', 'url'=>'http://www.soroptimisteurope.org'),
);
这是一件容易实现的事情,还是我的方法完全错了?
答案 0 :(得分:4)
你在这里走在正确的轨道上。所以,这里是如何让它做你想做的事情
在<script>
块中,我们希望以JSON
var federations = <?php echo json_encode($si_federations); ?>;
现在,当你运行countryfind
时,我们想要从该对象中提取值并显示它。所以让我们修改你的功能
function countryfind(){
var fed;
var selected = jQuery('#country_select option:selected').val();
if(federations[selected] !== undefined) fed = federations[selected];
else fed = {"name":"Default Name", "url":""}; //placeholders if it's not defined
jQuery('#countrykey').text(
selected + ' - ' + fed.name + ' ' + fed.url;
)};
我不知道你希望它如何显示(为了简单起见,我只是把它作为文本转储),但这可以获得你需要的数据,这样你就可以从那里获取数据
答案 1 :(得分:1)
您必须将php关联数组转换为js对象以供进一步参考。由于php在服务器上运行,并且您正在客户端执行每个操作,因此在页面加载后,您的PHP无用。你需要js var才能进一步引用它。 像这样:
<script>
var countries = [];
var country = {};
<?php foreach($si_federations as $k => $country): ?>
<?php foreach($country as $key=>$val): ?>
country['<?php echo $key; ?>'] = '<?php echo $val; ?>';
<?php endforeach; ?>
countries['<?php echo $k; ?>'] = country;
<?php endforeach; ?>
function countryfind(){
var keyVal = jQuery('#country_select option:selected').val();
jQuery('#countrykey').text('name: '+countries[keyVal]['name']+' url: '+countries[keyVal]['url']);
}
</script>
我希望它有所帮助