在我的编辑客户端窗口中,我将使用 ajax 实现选择,该选择将在选择部门时更新市政当局。然而,当执行ajax时,返回的信息实际上是我在控制器中使用的脚本。下面是edit-clientController中的脚本代码:
<?php
if ($_SESSION['user']['ordenes'] == 1) {
if (count($_POST) > 0) {
if (isset($_POST['nombres']) && isset($_POST['apellidos']) && isset($_POST['direccion']) && isset($_POST['telefono']) && isset($_POST['nit']) && isset($_POST['genero']) && isset($_POST['correo'])) {
$nombres = trim(strtoupper($_POST['nombres']));
$apellidos = trim(strtoupper($_POST['apellidos']));
$direccion = trim($_POST['direccion']);
$telefono = trim($_POST['telefono']);
$nit = trim($_POST['nit']);
$genero = $_POST['genero'];
$correo = trim($_POST['correo']);
if ($nit == '') {
$nit = NULL;
}
if ($nombres == '' || $apellidos == '') {
echo '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times-circle-o"></i></button>
<b>Error:</b> Rellene todos los campos.
</div>';
exit;
} else {
require_once 'models/clienteModel.php';
$e = new Cliente();
$update = $e->updateCliente($idItem, $nombres, $apellidos, $nit, $telefono, $direccion, $correo, $genero);
$e = null;
if ($update == true) {
echo '
<script>
$(location).attr("href","' . BASE_DIR . 'editar-cliente/' . $idItem . '-' . slug($nombres) . '/update");
</script>
';
} else {
echo '<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true"><i class="fa fa-times-circle-o"></i></button>
<b>Error:</b> No se pudo actualizar el registro, recarge la página e inténtelo nuevamente.
</div>';
}
}
}
} else {
require_once 'models/clienteModel.php';
$c = new Cliente();
$cliente = $c->getCliente($idItem);
$c = null;
$c = new Cliente();
$tipos = $c->getTipos();
$c = null;
$c = new Cliente();
$departamento = $c->getDepartamentos();
$c = null;
if (count($cliente) > 0) {
require_once 'views/header.php';
require_once 'views/clientes-editar.php';
require_once 'views/footer.php';
}
}
} else {
require_once 'views/404.php';
}
?>
<script>
var selectElement = document.getElementById("departamentos");
var lastSearchTerm = "";
var selectedMun = $("municipio").val();
function loadMunicipios() {
var selectedDepartamento = $("#departamento").val();
if (selectedDepartamento !== lastSearchTerm) {
lastSearchTerm = selectedDepartamento;
$("#municipios").prop("disabled", true).attr("placeholder", "Cargando...");
$.ajax({
url: 'ClientesEditarMunicipios',
type: "POST",
data: {
finca: selectedDepartamento
}
}).done(function(response) {
// No es necesario dividir la cadena, ya que recibes un array directamente
updateMunicipiosDropdown(response);
console.log(response);
$("#municipio").prop("disabled", false).attr("placeholder", "Municipio");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error("Error en la llamada AJAX:", textStatus, errorThrown);
console.log("Respuesta del servidor:", jqXHR.responseText);
});
}
}
function updateMunicipiosDropdown(municipiosList) {
// Verificar si municipiosList está definido y no es nulo
if (municipiosList) {
// Intentar parsear la cadena JSON
try {
var parsedData = JSON.parse(municipiosList);
if (parsedData.success && parsedData.data.length > 0) {
var municipios = parsedData.data;
$("#municipio").empty();
for (var i = 0; i < municipios.length; i++) {
var idGenerico = municipios[i]["ID_GENERICO"];
var nombre = municipios[i]["NOMBRE"];
$("#municipio").append($('<option>', {
value: idGenerico,
text: nombre
}));
}
} else {
console.error("La respuesta no contiene datos válidos.");
}
} catch (error) {
console.error("Error al parsear la lista de municipios como JSON:", error);
}
} else {
console.error("La lista de municipios no está definida o está vacía.");
}
}
// Evento para manejar la selección en "departamentos"
$("#departamento").on("change", function() {
loadMunicipios();
});
</script>
该脚本在另一节测试过,运行正常。 URL代码:“CustomersEditMunicipalities”如下:
<?php
date_default_timezone_set('America/Guatemala');
if (isset($_POST['finca'])) {
$buscar = $_POST['finca'];
require_once 'models/clienteModel.php';
$p1 = new Cliente();
$resultados = $p1->getMunicipios($buscar);
$p1 = null;
error_log(print_r($resultados));
header('Content-Type: application/json');
echo json_encode($resultados);
exit;
}
预期它会返回一个具有适当格式的 json,以便能够在数组中遍历它,并能够在名为 #municipios 的选择中迭代它,但它在控制台中打印的内容“console.log(response )”是这样的:
<script>
var selectElement = document.getElementById("departamentos");
var lastSearchTerm = "";
var selectedMun = $("municipio").val();
function loadMunicipios() {
var selectedDepartamento = $("#departamento").val();
if (selectedDepartamento !== lastSearchTerm) {
lastSearchTerm = selectedDepartamento;
$("#municipios").prop("disabled", true).attr("placeholder", "Cargando...");
$.ajax({
url: 'ClientesEditarMunicipios',
type: "POST",
data: {
finca: selectedDepartamento
}
}).done(function(response) {
// No es necesario dividir la cadena, ya que recibes un array directamente
updateMunicipiosDropdown(response);
console.log(response);
$("#municipio").prop("disabled", false).attr("placeholder", "Municipio");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.error("Error en la llamada AJAX:", textStatus, errorThrown);
console.log("Respuesta del servidor:", jqXHR.responseText);
});
}
}
function updateMunicipiosDropdown(municipiosList) {
// Verificar si municipiosList está definido y no es nulo
if (municipiosList) {
// Intentar parsear la cadena JSON
try {
var parsedData = JSON.parse(municipiosList);
if (parsedData.success && parsedData.data.length > 0) {
var municipios = parsedData.data;
$("#municipio").empty();
for (var i = 0; i < municipios.length; i++) {
var idGenerico = municipios[i]["ID_GENERICO"];
var nombre = municipios[i]["NOMBRE"];
$("#municipio").append($('<option>', {
value: idGenerico,
text: nombre
}));
}
} else {
console.error("La respuesta no contiene datos válidos.");
}
} catch (error) {
console.error("Error al parsear la lista de municipios como JSON:", error);
}
} else {
console.error("La lista de municipios no está definida o está vacía.");
}
}
// Evento para manejar la selección en "departamentos"
$("#departamento").on("change", function() {
loadMunicipios();
});
</script>
这实际上是 edit-clientController 代码之后的整个脚本,但我不明白为什么它将其作为“响应”。它应该返回给我(并在另一部分中返回)的是一个 json 格式的数组,我可以遍历它并将其转换为 select
我尝试在初始化视图的 else 之前放置一个“退出”,但现在它不能直接到达补充 ajax 的控制器。 如果有必要我可以分享ajax功能正常工作的控制器。
您的 ClientesEditarMunicipios 端点很可能出现错误或一次返回太多内容。
最好的方法是隔离问题并找出导致问题的线路。
<?php
date_default_timezone_set('America/Guatemala');
if (isset($_POST['finca'])) {
// $buscar = $_POST['finca'];
// require_once 'models/clienteModel.php';
// $p1 = new Cliente();
// $resultados = $p1->getMunicipios($buscar);
// $p1 = null;
$resultados = [
'result array element 1',
'result array element 2',
'result array element 3',
'result array element 4',
];
// error_log(print_r($resultados));
// header('Content-Type: application/json');
echo json_encode($resultados);
exit;
}