我正在使用codeigniter和grocerycrud。
我有一个视图,在这个视图中我有一些下拉列表,这些下拉列表是从控制器馈送的:
public function programar_ruta()
{
if($this->model_privilegios->validar_usuario()==true)
{
$data['destinos'] = $this->model_querys_usuario->get_destinos();
$this->load->view('usuario/dynamic_form2',$data);
}
}
我的型号功能代码:
public function get_destinos ()
{
$this-> db ->select('*');
$this-> db ->from('destinos');
$this -> db -> where('empresa', $_SESSION['empresa']);
$query = $this->db->get();
return $query->result();
}
在我的表单中,我有一个下拉菜单和一个指向控制器功能的按钮,可以添加一个新的"Destino":
<td width="18%" align="left">
<select name="destinos[]" id="origen0">
<?php foreach($destinos as $row)
{ echo '<option value="'.$row->nombre.'">'.$row->nombre.'</option>'; } ?>
</select>
<input type="button" value="..." onClick="window.open
('<?php echo base_url()?>index.php/usuario/destinos/add','Nuevo Destino','width=800,height=600')" title="Agregar nuevo destino"/></td>
代码"index.php/usario/destinos/add'"正指向一个标准的grocerycrud函数。
我的问题是:有没有一种方法可以在不刷新窗口的情况下将新元素添加到下拉选项中?
以下是我将带您了解的内容:
1) 。打开的窗口会显示一个表单,该表单会将目标添加到数据库中。
2) 。计时器脚本将等待窗口关闭,然后获取新的destino并将其添加到菜单中。
3) 。您需要添加处理JS请求的服务器端脚本。。。
所以——!首先,你会想去掉"onClick",并在一个单独的地方处理你的JS-让我们从改变开始:
<input type="button" value="..." onClick="window.open([...]
至:
<input type="button" id="newDestino" />
现在,在你的JS中,你需要给它一个点击处理程序:
$("#newDestino").click(function(){
var desinoMas = window.open('/index.php/usuario/destinos/add','Nuevo Destino','width=800,height=600');
var windowCloseChecker = setInterval(function() {
if (win.closed) {
clearInterval(timer);
addDestino();
}
}, 1000);
});
执行<?php echo base_url() ?>
的部分不是必需的,只需使用absolutepath:'/index.php'---如果我遗漏了什么,并且真的是必要的-只需将脚本扔到页面底部的<script>
标签中,然后像正常一样使用<?php echo
现在,让我们定义我们的addDestino函数:
function addDestino(){
$.ajax({
url : "index.php/usuario/destinos/updateClientMenu",
method: "POST" // this is really irrelevant,
success: function(response){
$("#origen0").html(response);
}
});
}
您将看到我将脚本命名为index.php/usuario/destinos/updateClientMenu
——您可以随心所欲地命名它,但该脚本需要生成一些简单的html来添加到DOM中。
您可以使用以下代码,这些代码对您来说应该非常熟悉-!
<?php
//[...] You'll obviously need to re-query for the destinos, here.
foreach($destinos as $row)
{ $response .= '<option value="'.$row->nombre.'">'.$row->nombre.'</option>'; }
echo $response;
?>
您注意到,在回显之前,我将所有$destinos
存储在一个变量中。
现在,echo $response
反馈到我们的addDestinos
函数中的success
函数中-!!-它只是获取该响应并用新的html替换菜单的html。
所以,为了澄清和总结它,一切都是这样的:
单击该按钮,会打开一个带有表单的新窗口——填写完表单后,它会提交以创建一个新的destino。当窗口关闭时,脚本会注意到窗口已关闭,并要求服务器提供新的desinos菜单。服务器以刷新的destinos列表作为响应。
现在-!这个脚本可以改进-!
所以,我建议你自己试试,作为一种练习:
不要获取整个列表,只需获取最近添加的destino。(在这种情况下,您需要使用$.append()
而不是$.html()
)
祝你好运!
我认为ajax是最好的方法,您可以尝试以下方法:
...
var addedData = $(this).closet('origen0').find('input_id').val();
$.ajax({
url: <?php echo base_url('index.php/usuario/destinos/add');?>,
type: 'POST',
data: addedDate
...