无法在javascript jQuery中读取PHP结构数组

时间:2015-11-30 14:26:35

标签: javascript php jquery html5

我试图用jQuery读取并显示一个PHP数组,显式地是一个解析的SRT字幕文件。在console.log(data)成功响应后,我可以看到所有数据一起ajax,但我想操纵数据。 我的jQuery代码:

var jsonURL = JSON.stringify(data);
        $.ajax({
            type: "POST",
            url: "parser_srt.php",
            data: {url: jsonURL}, 
            cache: false,

            success: function(data){
                console.log(data);
                var cont = 0;
                var data = JSON.parse(data)
                for(var i = 0; i < data.length; i++) {
                    n_ = data[i].number;
                    i_ = data[i].startTime;
                    o_ = data[i].stopTime;
                    t_ = data[i].text;

                    //is = srtToSeconds(i_);
                    //os = srtToSeconds(o_);

                    var startUp = [{ "start": i_, "end": o_, "text": t_}]; 
                    subtitles_1.push(new paragraph(i + 1, startUp[0].start, startUp[0].end, startUp[0].text));

                    if(flag == 1){
                        var startUp_trans = [{ "start": i_, "end": o_, "text": ' ' }];
                        subtitles_2.push(new paragraph(i + 1, startUp_trans[0].start, startUp_trans[0].end, startUp_trans[0].text));
                    }
                    //cont++;
                }
            }
        });

PHP代码就是这个代码:

<?php 

define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME',      1);
define('SRT_STATE_TEXT',      2);
define('SRT_STATE_BLANK',     3);

$url = json_decode($_POST['url']);

$lines   = file($url);

$subs    = array();
$state   = SRT_STATE_SUBNUMBER;
$subNum  = 0;
$subText = '';
$subTime = '';

foreach($lines as $line) {
    switch($state) {
        case SRT_STATE_SUBNUMBER:
            $subNum = trim($line);
            $state  = SRT_STATE_TIME;
            break;

        case SRT_STATE_TIME:
            $subTime = trim($line);
            $state   = SRT_STATE_TEXT;
            break;

        case SRT_STATE_TEXT:
            if (trim($line) == '') {
                $sub = new stdClass;
                $sub->number = $subNum;
                list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
                $sub->text   = $subText;
                $subText     = '';
                $state       = SRT_STATE_SUBNUMBER;

                $subs[]      = $sub;
            } else {
                $subText .= $line;
            }
            break;
    }
}
echo json_encode($subs);
?>

为什么我无法在jQuery中获取结构数组中的数据,我不明白?

谢谢

2 个答案:

答案 0 :(得分:2)

我想我会发表评论作为答案...

首先关闭......

在您的ajax通话中设置dataType: 'JSON',下的cache: false,

无需执行JSON.parse(data)

最后,将success: function(data_)更改为success: function(data)并在循环中迭代data

此时一切都应该有效。

答案 1 :(得分:1)

你的成功函数定义了data_&amp;你是console.logging data_但是你正在循环数据

success: function(data_){
console.log(data_);

...

for(var i = 0; i < data.length; i++) {