您好,我有一个返回未定义消息的脚本。在 consol 中,它返回 jsondata,但是当我发出警报或尝试验证它时,它不起作用。
$(function() {
$(".aplica_bt").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
$.ajax({
url: href,
datatype: "json",
success: function(msg) {
alert(msg.exista);
if (msg.exista == "yes") {
alert('ai aplicat');
}
if (msg.aplicat == "yes") {
$('#modal_succes').modal('show');
}
},
});
});
});
这里也是返回 json 的 php 代码
<?php
$id_c=$_GET['id_c'];
$id_j=$_GET['id_j'];
$stmt=$dbh->prepare("SELECT * FROM Aplicatii where id_c=:id_c and id_j=:id_j");
$stmt->bindParam(":id_c",$id_c);
$stmt->bindParam("id_j",$id_j);
$stmt->execute();
if($row=$stmt->fetch())
{
$arr = array('exista' => 'yes');
echo json_encode($arr);
}
else
{
$stmt=$dbh->prepare("INSERT INTO Aplicatii (id_c,id_j) VALUES (:id_c,:id_j)");
$stmt->bindParam(":id_c",$id_c);
$stmt->bindParam("id_j",$id_j);
$stmt->execute();
$arr = array('aplicat' => 'yes');
echo json_encode($arr);
}
?>
以及console.log
的响应:
{"exista":"yes"}
最佳答案
当 console.log(msg)
返回 {"exista":"yes"}
时,它不是一个对象
,它是一个字符串
。因此,尝试访问属性(例如 msg.exista
)将返回 undefined
。
当您在 AJAX 请求中设置错误的 dataType
(在示例中正确设置为 JSON
)时,可能会发生这种情况。
所以问题出在 PHP 端,您需要将正确的 Content-Type
添加到响应 headers
中。
header("Content-Type: application/json");
关于jquery - ajax成功: function (msg) undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39526274/