我是json的新手。我从json格式的PHP代码中获取数据..
[
{
"Title": "New Event",
"TYPE": "info",
"StartsAt": "16 November 201512:00",
"EndsAt": "25 November 201512:00"
},
{
"Title": "Party",
"TYPE": "warning",
"StartsAt": "25 November 2015 09:30",
"EndsAt": "25 November 2015 5:30"
},
]
我有一个javascript文件demo.js
我想在js文件中接收这些数据,目前数据是硬编码的。我想显示我从db获取的事件。
vm.calendarView = 'month';
vm.calendarDay = new Date();
vm.events = [
{
title: 'An event',
type: 'warning',
//startsAt: moment().startOf('week').subtract(2, 'days').add(8, 'hours').toDate(),
//endsAt: moment().startOf('week').add(1, 'week').add(9, 'hours').toDate(),
startsAt:new Date(2015,10,1,1),
endsAt:new Date(2013,5,1,1),
draggable: true,
resizable: true
}, {
title: '<i class="glyphicon glyphicon-asterisk"></i> <span class="text-primary">Another event</span>, with a <i>html</i> title',
type: 'info',
startsAt: moment().subtract(1, 'day').toDate(),
endsAt: moment().add(5, 'days').toDate(),
draggable: true,
resizable: true
}, {
title: 'This is a really long event title that occurs on every year',
type: 'important',
startsAt: moment().startOf('day').add(7, 'hours').toDate(),
endsAt: moment().startOf('day').add(19, 'hours').toDate(),
recursOn: 'year',
draggable: true,
resizable: true
}
];
答案 0 :(得分:0)
如果问题大致是“我如何从我的数据库中获取数据并在Javascript中将其作为JSON输出”,那么希望以下伪代码能够指导您正确的方向。
<?php
include 'db.php';
$json=array();
/* Query the db */
$sql='select * from `events`;';
$res=$db->query( $sql );
if( $res ){
while( $rs=$res->fetch_object() ){
$json[]=array(
'title' => $rs->title,
'type' => $rs->type,
'startsAt' => $rs->startsAt,
'endsAt' => $rs->endsAt,
'draggable' => $rs->draggable,
'resizable' => $rs->resizable
);
}
}
$db->close();
$js_json_var=json_encode( $json, JSON_FORCE_OBJECT );
?>
<html>
<head>
<title></title>
<script>
var json=<?php echo $js_json_var;?>;
/* Other js code */
</script>
</head>
<body>
<h1>json</h1>
</body>
</html>
答案 1 :(得分:0)
Javascript:AJAX请求:
var events;
$.ajax({
url: '/data.php',
success: function(data){
events = JSON.parse(data);
}
});
data.php就像这样
$db = new PDO(/* init connection here */);
print json_encode($db->query('select * from `tablename`')->fetchAll(PDO::FETCH_ASSOC));
答案 2 :(得分:0)
// In javascript
$.ajax({
type: 'post',
url: 'data.php',
data: 'data',
cache: false,
success: function(data)
{
console.log(data);
}
});
// In data.php
header('Content-type: application/json');
$data = array();
$sql = "SELECT * FROM TABLE_NAME";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res))
{
$data[] = $row;
}
echo json_encode($data, true);