当我尝试在php文件中使用ajax时,我遇到了一个问题,该文件调用了另一个php文件。 这是php文件的代码:
<script>
function obtenerProductos(cat) {
parametros = {"idCat": cat};
$.ajax({
data: parametros,
url: '/bin/getProductos.php',
type: 'post',
beforeSend: function() {
$(".prods > form").html("Procesando, espere por favor...");
},
success: function(respuesta) {
$(".prods > form").html(respuesta);
}
});
}
function obtenerProducto(prod) {
parametros2 = {"idProd": prod};
$.ajax({
data: parametros2,
url: '/bin/getProducto.php',
type: 'post',
beforeSend: function() {
lista = $(".cPreview").html() + "<br/> Añadiendo...";
$(".cPreview").html(lista);
},
success: function(respuesta) {
lista = $(".cPreview").html()+ respuesta.nombre + "\t" + respuesta.precio + "<br/>" ;
$(".cPreview").html(lista);
precio = parseFloat($(".precioT").html()) + respuesta.precio;
$(".precioT").html(precio);
}
});
}
</script>
在这个脚本的第一个函数中,我调用第一个PHP(getProductos.php)来获取类别的所有产品并接收一个在表单中打印的html。 第二个函数调用另一个php(getProducto.php)来获取所选产品的所有信息,并将其打印在另一个div中。 这里有名为。
的PHP文件getProductos.php (这有效)
<?php
include '../funciones.php';
$recibido = $_POST['idCat'];
echo obtenerProductosCategorias($recibido);
?>
getProducto.php (不要工作)
<?php
include '../funciones.php';
$recibido = $_POST['idProd'];
echo obtenerProductos($recibido);
?>
此代码的2个功能:
function obtenerProductosCategorias($idCat) {
conectDB();
$string = "";
$sql = 'select * from Productos where id_categoria="' . $idCat . '";';
$resultado = mysql_query($sql);
while ($row = mysql_fetch_array($resultado)) {
$string = $string . "<input type='button' onclick='obtenerProducto(" . $row["id_producto"] . ");return false;' value='" . $row['nombre_producto'] . "' />";
}
return $string;
closeDB();
}
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}
我在PHP内部发出警报,检查一切正常,但第二个函数没有输入他的PHP,它返回undefined undefined而不显示PHP的任何警告,这就是为什么我认为第二个函数有一些问题要达到他的PHP,但URL正确,文件位于正确的位置。
感谢阅读并抱歉我的英语。
答案 0 :(得分:0)
在分配任何东西之前尝试将$ resultado定义为数组。不确定,但在某些配置中,这确实打破了PHP。
function obtenerProductos($idProd) {
conectDB();
$sql = 'select * from Productos where id_producto="' . $idProd . '";';
$resul = mysql_query($sql);
$resultado = array();
while ($row = mysql_fetch_array($resul)) {
$resultado["nombre"] = $row["nombre_producto"];
$resultado["precio"] = $row["coste_producto"];
}
return json_encode($resultado);
closeDB();
}