我有一个foreach循环,可从JSON结构创建selects选项。
foreach ($categories['results'][0]['parameters'] as $key => $value) {
if(in_array($value['code'], $input_valid_names)){
switch ($value['type']) {
case 'select':
echo "<div class='coluna-2'>";
$options = [];
foreach ($value['options'] as $option_value => $option_name) {
$option = "<option data-marca='".$option_value."' value='".$option_value."'>".$option_name['pt']."</option>'";
array_push($options, $option);
}
echo "<label>".$value['labels']['pt'].(($value['required'])? '*' : '')."</label>";
echo "<select id='sel' name='".$value['code']."' ".(($value['required'])? 'required' : '').">";
echo "<option value>Escolha uma opção</option>";
foreach ($options as $o) {
echo $o;
}
echo "</select>";
echo "<br/><br/>";
echo "</div>";
break;
default:
break;
}
}
}
在带有标签 Modelo 的以下选择选项之一中,我需要从ajax响应中注入数据:
success: function(data) {
var obj0 = JSON.parse(data);
var obj = obj0.options;
for (var key in obj){
var opt = document.createElement('option');
opt.innerHTML = obj[key].pt;
opt.value = obj[key].pt;
sel.appendChild(opt);
}
}
但是,如果可能的话,我不知道该怎么做。
答案 0 :(得分:0)
在您的代码中,您对未定义的变量sel调用.appendChild:
sel.appendChild(opt);
像这样定义此变量:
success: function(data) {
var obj0 = JSON.parse(data);
var obj = obj0.options;
// get by id
var sel = document.getElementById('sel');
// or get by name
var sel = document.getElementsByName('name')[0];
for (var key in obj){
var opt = document.createElement('option');
opt.innerHTML = obj[key].pt;
opt.value = obj[key].pt;
sel.appendChild(opt);
}
}