我一直在寻找答案。
我有JSON字符串
"[{"id":"0"}]"
我试过
obj['id'] and obj.id
但这不起作用
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: 'doctorName=' + doctorName + '&dayOfEvent=' + date1,
type: "POST",
success: function (json) {
obj = JSON.parse(json.data)[0];
b = obj.id;
}
});
return true;
}
我错过了什么吗?
这是用于获取结果的php 修改
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
答案 0 :(得分:0)
你的JSON字符串实际上是否有开头和结尾&#34;在其中,或者你刚刚在那里添加它们来说明它是一个字符串?
假设我们的数据字符串实际上有&#34;,那么您只想使用语法
[{"id":"0"}]
答案 1 :(得分:0)
根据评论,该对象实际上是一个包含对象的数组
var str = "[{\"id\":\"0\"}]";
var obj = JSON.parse(str)[0];
alert(obj.id);
obj [&#34; id&#34;]也会有效,与obj.id相同
答案 2 :(得分:0)
试试这个:
<强> JS 强>
$.ajax({
url: 'php/checkdoctorappointmentonday.php',
data: {
doctorName: doctorName,
dayOfEvent: date1
},
type: "POST",
dataType: 'json',
success: function (data) {
console.log(data);
b = data.0.id;
}
});
<强> PHP 强>
<?php
$doctorName = $_POST['doctorName'];
$dayOfEvent = $_POST['dayOfEvent'];
// Query that retrieves events
$query = "SELECT COUNT(id) AS 'id'
FROM doctoravailability
WHERE start >='$dayOfEvent' AND start < DATE_ADD('$dayOfEvent', INTERVAL 1 DAY)
AND title = '$doctorName'
AND backgroundColor = 'red'
";
// connection to the database
try {
$bdd = new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($query) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
return $resultat->fetchAll(PDO::FETCH_ASSOC);
?>