gpt4 book ai didi

javascript - 使用javascript从php获取json数据

转载 作者:行者123 更新时间:2023-11-28 06:41:11 24 4
gpt4 key购买 nike

我是 json 新手。我正在从 php 代码中以 json 格式获取数据。

[
{
"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文件中接收这些数据,目前数据是硬编码的。我想显示从数据库获取的事件。

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
}
];

最佳答案

如果问题大致是“如何从数据库获取数据并在 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>

关于javascript - 使用javascript从php获取json数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33805976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com