使用Jquery将php字符串数据转换为Json对象

时间:2013-04-28 12:27:39

标签: php javascript jquery json

我需要从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 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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);
            }
        });
    }

您的案例中的错误消息是什么?

答案 2 :(得分: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对象。

答案 3 :(得分:0)

$data = preg_replace('@new Date\(([^\)]*)\)@', '"$1"', $data);
$data = json_decode($data, true);

结果:

  

新日期(2008,3,30,0,31,26)=&gt; “2008,3,30,0,31,26”