Ajax成功函数不能处理json答案



如果我将dataType设置为'json',并在我的PHP文件中打印任何我想要的(事件一个字母),成功函数工作,但如果我不打印任何其他除了json我需要,停止工作。我不能用其他打印的东西处理我的数据,因为它将答案转换为HTML,而不是JSON。我可以在网络中看到->回答JSON文件(只有当我不打印JSON旁边的任何东西时),但我不知道为什么在这种情况下,我甚至不能在成功函数中发出警报。

这是我的ajax,它只工作,因为我在服务器上打印'true':

$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
这是我的PHP代码:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
顺便说一下,有了这段代码,我在警报中得到了这个错误:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data

我使用jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)

如果你返回JSON,你只能回送JSON一次,而不是每次都通过循环。

如果只有一行,则不需要while循环。只需获取行并创建JSON。

您也不能回显任何其他内容,因此echo "true";行将打断它。

并且您的代码对sql注入非常开放。您应该使用带参数的预处理语句,我已经演示了如何这样做。

$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});

最新更新