我已经处理这个问题有一段时间了,但我在这里看不到解决方案。 我正在制作一个简单的列表应用程序,每当用户创建新项目时,都应该将其保存到数据库中。 问题是每个项目都有一个唯一的ID(自动递增),并且当该项目附加到列表时,该ID必须位于html代码上(其他函数需要使用它,因此当它上传到数据库时,那么应该选择ID并再次发送到原始html文件,但我不知道该怎么做(事实上,我不知道)。
这是我的 php/html 代码:
while($row = mysql_fetch_array($selectitems) ){
echo'<html>
<li class="iÂtem" data-id="';
echo $row['IDitem'];
echo '">
<div class="draggertab"><img src="imatges/botofletxa.jpg" width="30" height="30"></div>
<div class="deletetab"><img src="imatges/botocreu.jpg" width="30" height="30"></div>
<span class="item">';
echo $row['Text'];
echo'</span>
</li>
</html>';
}
JavaScript:
ajax.onreadystatechange=function() {
//la función responseText tiene todos los datos pedidos al servidor
if (ajax.readyState==4) {
//mostrar resultados en esta capa
AppendItem();
//llamar a funcion para limpiar los inputs
LimpiarCampos();
}
}
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//enviando los valores a registro.php para que inserte los datos
ajax.send("nombre="+nom+"&IDllista="+llista);
}
还有 PHP:
$con = mysql_connect($bd_host, $bd_usuario, $bd_password);
mysql_select_db($bd_base, $con);
//variables POST
$nom=$_POST['nombre'];
$IDllista = $_POST['IDllista'];
//registra los datos del empleados
$sql="INSERT INTO items (Text, IDllista) VALUES ('$nom', '$IDllista')";
mysql_query($sql,$con) or die('Error. '.mysql_error());
还有更多的代码,但我发布了我认为最重要的部分。现在一切正常,我只需要发送 ID 即可。
非常感谢!!
最佳答案
您应该避免使用 mysql_* 并使用 PDO。自 PHP5.5 起 mysql_ 函数已弃用
无论如何,您可以检索使用mysql_insert_id()
生成的最后一个ID并将其返回到您的ajax处理程序,然后您可以使用var id = xmlhttp.responseText;
获取它>
PHP:
$sql="INSERT INTO items (Text, IDllista) VALUES ('$nom', '$IDllista')";
mysql_query($sql,$con) or die('Error. '.mysql_error());
echo mysql_insert_id(); // return the ID
JS:
ajax.onreadystatechange=function() {
if (ajax.readyState==4) {
....
var id = ajax.responseText; // get it
}
}
关于javascript - 使用ajax将mysql结果返回给php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20711536/