我需要從PHP獲取一些Json數據到jquery。使用Jquery將php字符串數據轉換爲Json對象
我需要JavaScript方法中的以下格式。
function returnJson()
{
return {
events: [
{
"id": 1,
"start": new Date(2013, 4, 26, 12),
"end": new Date(2013, 4, 26, 13, 30),
"title": "Lunch with Mike"
},
{
"id": 2,
"start": new Date(2013, 4, 27, 14),
"end": new Date(2013,4, 27, 14, 45),
"title": "Dev Meeting"
}]
};
}
對於這個我做下面的事情在javascript:
在PHPfunction returnJson()
{
var eventResult = $.getJSON("../PHP/PhpAction.php?f=fetchCalendarEvent");
return eventResult;
}
:
function fetchCalendarEvent()
{
$tablename = "tb_calendar";
$sql = "SELECT eventId,userId,enentName,eventText,EXTRACT(YEAR FROM startTime) AS startyear,EXTRACT(MONTH FROM startTime) AS startMonth,EXTRACT(DAY FROM startTime) AS startDay,EXTRACT(HOUR FROM startTime) AS startHour,EXTRACT(MINUTE FROM startTime) AS startMin,EXTRACT(YEAR FROM endTime) AS endyear,EXTRACT(MONTH FROM endTime) AS endMonth,EXTRACT(DAY FROM endTime) AS endDay,EXTRACT(HOUR FROM endTime) AS e`enter code here`ndHour,EXTRACT(MINUTE FROM endTime) AS endMin FROM ".$tablename." WHERE userId='".$_SESSION['userid']."' AND isActive=1";
$q = mysql_query($sql);
$i=1;
$eventData="{events: [";
if (!mysql_num_rows($q)) {
echo 'No records found';
}
else
{
while ($row = mysql_fetch_assoc($q)) {
$eventData.="{'id':".$row['eventId'].",";
$eventData.="'end': new Date(".$row['startyear'].",".$row['startMonth'].",".$row['startDay']."," .$row['startHour'].",".$row['startMin']."),";
$eventData.="'start': new Date(".$row['endyear'].",".$row['endMonth'].",".$row['endDay'].",".$row['endHour'].",".$row['endMin']."),";
$eventData.="'title':'".$row['enentName']."'},";
$i++;
}
}
$eventData= rtrim($eventData, ",");
$eventData.="]}";
echo json_decode($eventData);
}
我檢查的螢火php的方法返回的數據,如:
{ events: [ {
'id': 2,
'end': new Date(2013, 4, 27, 18, 38),
'start': new Date(2013, 4, 27, 18, 38),
'title': 'test'
}, {
'id': 3,
'end': new Date(2013, 4, 23, 11, 0),
'start': new Date(2013, 4, 23, 14, 15),
'title': 'testing23'
}
] }
任何人都可以請 幫我。我是新的PHP。任何幫助將不勝感激。
可能你的web服務器確實返回了JSON的錯誤html頭文件。也許你應該使用'jQuery.ajax()' - 它有更多的選項來「調整」... – rantanplan 2013-04-28 12:34:41
將數據存儲在關聯數組中並對其運行json_encode()。 – powerbuoy 2013-04-28 12:35:13
對不起,它也無法正常工作..我認爲我的代碼中有一些主要問題。 – 2013-04-28 12:37:58