0

我需要从 PHP 到 jquery 获取一些 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 中执行以下操作:

function returnJson()
{
    var eventResult = $.getJSON("../PHP/PhpAction.php?f=fetchCalendarEvent");
    return eventResult;
}

在 php 中:

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

我在 firebug 中检查 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新手。任何帮助将不胜感激。

4

4 回答 4

5

Php 有一个名为 json_encode 的函数,它将处理 json 输出的生成。

这是一个例子:

$o = array();
$o['events'] = array();
while ($row = mysql_fetch_assoc($q))
{
    $event = array();
    $event['id'] = $row['id'];
    $event['start'] = "new Date(".$row['startyear'].",".$row['startMonth'].",".$row['startDay']."," .$row['startHour'].",".$row['startMin'].")";
    $event['end'] = "new Date(".$row['endyear'].",".$row['endMonth'].",".$row['endDay'].",".$row['endHour'].",".$row['endMin'].")";
    $event['title'] = $row['title'];

    $o['events'][] = $event;
}

return json_encode($o);

并且 javscript 代码可能是这样的:

function returnJson()
{
    var events = $.getJSON("../PHP/PhpAction.php?f=fetchCalendarEvent");

    for (var i = 0; i < events.length; i++) {
        var event = events[i];
        event.start = eval(event.start);
        event.end = eval(event.end);

        events[i] = event;
    }

    return events;
}
于 2013-04-28T12:38:03.623 回答
0

您不能在 json 中格式化日期对象。一种选择是使用时间戳并在解析 json 期间对其进行转换。

如果你检查http://jsonlint.com/你会看到你的 json 给出了错误。

您的语法是 Javascript 对象表示法,而不是 json 表示法。Javascript 可以使用json.stringify函数生成 json。

我只是仔细检查了一下,如果您对 javascript 对象进行字符串化,则会发生以下转换:

var date = new Date(2013, 4, 26, 12);
var string = JSON.stringify(date);
console.log(string);
//output = 2013-05-26T10:00:00.000Z
console.log(JSON.parse(string));
//will again output 2013-05-26T10:00:00.000Z

因此,您可以使用 JSON.stringify 将日期对象转换为字符串。但是您不能将它们格式化回 Date 对象。

于 2013-04-28T12:54:43.837 回答
0

在将 AJAX 数据发送到浏览器时,您应该添加适当的标头和 MIME 类型:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

以下是一些关于如何使用发送到浏览器的数据的示例代码:

    function requestData() {
        $.ajax({
            url: url,
            dataType: 'json',
            success: function(json) {
                events = json.events;

                useData(events);
            },
            error: function (xhr, status, error) {
                alert('Status: ' + status +' Error: ' + error);
            }
        });
    }

在您的情况下,错误消息说明了什么?

于 2013-04-28T12:37:38.110 回答
0
$data = preg_replace('@new Date\(([^\)]*)\)@', '"$1"', $data);
$data = json_decode($data, true);

结果:

新日期(2008,3,30,0,31,26) => "2008,3,30,0,31,26"

于 2015-11-06T12:18:31.170 回答