gpt4 book ai didi

javascript - 如何将新窗口中创建的新元素的数据返回到下拉列表中

转载 作者:行者123 更新时间:2023-12-03 11:30:48 24 4
gpt4 key购买 nike

我正在使用 codeigniter 和grocerycrud。

我有一个 View ,在这个 View 中我有一些下拉菜单,这些下拉菜单是从 Controller 提供的:

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();
}

在我的表单内,我有下拉菜单和一个按钮,标题为 Controller 功能,允许添加新的“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/usuario/destinos/add'”正在前往标准的grocerycrud函数。

我的问题是:有没有办法在不刷新窗口的情况下将新元素添加到下拉选项中?

最佳答案

是的,通过 AJAX -!

以下是我将引导您完成的内容:

1).打开的窗口显示一个表单,它将目标添加到数据库中。

2).计时器脚本将等待窗口关闭,然后获取新的目的地并将其添加到您的菜单中。

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() ?>不是必需的 - 只需使用绝对路径:'/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反馈到success功能在我们的 addDestinos功能-!! - 它只是获取该响应并用新的 HTML 替换菜单的 html。

所以,为了澄清和总结它,一切都是这样的:

单击该按钮,将打开一个包含表单的新窗口 - 填写表单后,它会提交以创建新的目的地。当窗口关闭时,脚本会注意到窗口已关闭,并向服务器请求新的桌面菜单。服务器以刷新的目的地列表进行响应。

现在-!这个脚本可以改进-!

所以,我建议您自己尝试一下,作为练习:

无需获取整个列表,只需获取最近添加的目的地。(在这种情况下,您需要使用 $.append() 而不是 $.html() )

祝你好运-!

关于javascript - 如何将新窗口中创建的新元素的数据返回到下拉列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26741945/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com