有你需要做相当多的东西,下面的方法真的只有一小一次性的项目,它不会很好地进行缩放。它将概述您需要采取的基本步骤。
你需要写一个简单的服务,接受选定日期的查询字符串PARAM。
服务应该使用类似PDO的东西来从数据库中的数据包含查询。
我建议从这里开始: https://phpdelusions.net/pdo
基本可以用准备好的声明中安全使用日期值作为选择标准。
然后你会使用数组构造你的响应。在这个例子中,关联数组有一个名为“data”的键,其中包含一个带有两个键“name”和“value”的关联数组的索引数组。
然后,您的标题设置为“内容类型:应用程序/ json'so浏览器知道如何处理的响应。
最后,您希望使用json_encode函数将嵌套数据数组处理为JSON。
最裸露的骨头的服务应该是这样的:
<?php
date_default_timezone_set('UTC');//Set time zone appropriately
//Get date from url , I set a default if there is no date, you mat want to throw an error...
//Error throw if data param missing!
$myDate = $_GET['date'];
//Query DB to get back a result set. The sample data below is allows you to get a JSON respons back.
//check out this tutorial to get a good understanding of how to use PDO to get your data from the DB: https://phpdelusions.net/pdo
//This represents the data from your query.
$foo = Array(
data => Array(
Array(
'name' => 'Bar',
'value' => 42,
),
Array(
'name' => 'Baz',
'value' => -42,
)
)
);
//Make sure you set the header and then echo the content, there should be no extra white space after the header is set!
header('Content-Type: application/json');
echo json_encode($foo);
?>
假设这是位于foo.com/get-events.php,以下请求:
$.ajax({
url: 'http://foo.com/get-events.php',
method: 'GET',
dataType: 'json'
})
.done(function(data) {
//Use data to set calendar!!!
console.log('Data: ', data);
});
将输出跟随JSON:
{"data":[{"name":"Bar","value":42},{"name":"Baz","value":-42}]}
此外,这里是一个简单的结构化项目,促进代码重用和覆盖是上面概述的主题。它的好的部分,你可能可以复制/粘贴和改变,以满足您的需求
- Getting/Setting data using PDO
- A simple service that handles the data from the DB
- JSON response helper Class
- DB/Table Info and setup
建立与您的JSON元素来自你的SQL查询的结果。 – chris85
不知道该怎么做,你有链接教程或例子,你可以回答? – Shane
看看:http://stackoverflow.com/questions/6281963/how-to-build-a-json-array-from-mysql-database不要使用那里使用的'mysql_ *'函数,那答案是5岁,使用PDO或mysqli。 – chris85