使用ajax以n种形式显示n个同名div



我需要显示字段的内容:"nombrePlato;在div:<div id = 'carrito'>中,但是存在一个问题;carito";divs。它只显示第一个div中的字段。如何显示对应形式的div中字段的内容?

menus.php

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilos.css">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<?php
$restaurante=$_GET['restaurante'];
chdir(getcwd()."/".$restaurante);
$id_fichero= @fopen("menus.txt","r") or die("<B>El fichero no se pudo abrir");
?>
<?php
$j=0;
while (!feof($id_fichero))
{            
if(($linea=trim(fgets($id_fichero,256),"nr"))!=false) 
{
echo("<button type='button' class='accordion'>".$linea."</button>");                
echo("<div class='panel'>");
$id_fichero2= @fopen($linea.".txt","r") or die("<B>El fichero no se pudo abrir");
while (!feof($id_fichero2))
{
echo("<form method='post' id='platos'>");
if(($linea2=trim(fgets($id_fichero2,256),"nr"))!=false)
{
echo("<button type='button' id='plato' name='plato' class='plato'>".$linea2."</button><br>");
echo("<input type='hidden' id='nombrePlato' name='nombrePlato' value='".$linea2."'>");                    
echo("<div id='carrito'>");
echo("</div>");
}
echo("</form>"); 
}
echo ("</div>");
}
$j++;
}            
?>
<script src="collapsible.js"></script>
</body>
</html>

anadirCarrito.php

<?php
$nombrePlato=$_POST["nombrePlato"];
echo($nombrePlato);
?>

ajax.js

$(document).on('ready',function(){    
$('.plato').click(function(){
var url = "anadirCarrito.php";
$.ajax({                        
type: "POST",                 
url: url,   
data: $(this).closest("form").serialize(), 
success: function(data)             
{ 
$('#carrito').html(data);  
}
});
});
});

在有效的html中,不能有多个具有相同id的元素。在这种情况下,只能识别第一个元素。相反,给div一个类或唯一的id并使用它。

echo("<div class='carrito'>");
echo("</div>");

并将其填充到js 中

$(document).on('ready',function(){    
$('.plato').click(function(){
var url = "anadirCarrito.php";
var $form = $(this).closest("form");
$.ajax({                        
type: "POST",                 
url: url,   
data: $form.serialize(), 
success: function(data)             
{ 
$form.find('.carrito').html(data);  
}
});
});
});

您还应该考虑为表单、按钮和循环中动态生成的任何其他元素提供唯一的id,以避免此类问题。

最新更新