JSON将PHP数组编码为JAVASCRIPT变量

时间:2014-01-20 19:20:46

标签: javascript php mysql json

请有人亲切地说明我创建并输出到 jsondata.php 的以下结果如何可以放入JavaScript中的变量中,以便我可以索引通过结果并在我的网站中使用Div。

需要的变量是:

$ lastplayed中的所有内容和$ secsemain的结果

我尝试使用下面的代码访问Javascript中的数据,...我知道它很糟糕!!

TEST1

<script>
url = jsondata.php;
var arr;
arr = <?php echo json_decode($lastplayed,TRUE); ?>;
</script>

以下是生成JSON数据的文件

FILE1(dblastplayedarray.php)

<?php

date_default_timezone_set('Europe/London');

require_once("DbConnect.php");

$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ";

$result = $db->query($sql);

$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist']         = $row->artist;
$lastplayed[$i]['title']          = $row->title;
$lastplayed[$i]['label']          = $row->label;
$lastplayed[$i]['albumyear']      = $row->albumyear;
$lastplayed[$i]['date_played']    = $row->date_played;
$lastplayed[$i]['duration']       = $row->duration;
$lastplayed[$i]['picture']        = $row->picture;
$i++;
}

$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>

文件2(jsondata.php)

<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>

2 个答案:

答案 0 :(得分:1)

首先,您不希望生成对PHP脚本的连续请求,只是为了获得当前歌曲的剩余时间。最好让JavaScript处理它。

您的JavaScript必须决定两件事:

  1. 何时获取下一批歌曲描述
  2. 如何获取
  3. 可能的解决方案是:

    让你的JS代码计算当前歌曲结束的时间。 当此时间达到零时,通过PHP查询您的数据库以获取下一批歌曲 收到更新后,再次计算当前歌曲结束的时间并等待它达到零(使用计时器)。

    要从PHP获得结果,最好使用Ajax来避免完全刷新页面。

    把所有这些放在一起,你应该有类似的东西:

    的JavaScript

    var PlayList = function (onUpdate, onError)
    {
        // store user callbacks
        this.onUpdate = onUpdate; 
        this.onError  = onError;
    
        // setup internal event handlers
        this.onSongEnd = onSongEnd.bind (this);
    
        // allocate an Ajax handler
        try
        {
            this.ajax = window.XMLHttpRequest
                ? new XMLHttpRequest()
                : new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            // fatal error: could not get an Ajax handler
            this.onError ("could not allocated Ajax handler");
        }
        this.ajax.onreadystatechange = onAjaxUpdate.bind(this);
    
        // launch initial request
        this.onSongEnd ();
    
        // ------------------------------------------
        // interface
        // ------------------------------------------
    
        // try another refresh in the specified amount of seconds
        this.retry = function (delay)
        {
            setTimeout (this.onSongEnd, delay*1000);
        }
    
        // ------------------------------------------
        // ancillary functions
        // ------------------------------------------
    
        // called when it's time to refresh the playlist
        function onSongEnd ()
        {
            // ask for a playlist update
    
            this.ajax.open('GET', 'playlist.php', // <-- reference your PHP script here
                           true);
            this.ajax.send(null);       
        }
    
        // called to handle Ajax request progress
        function onAjaxUpdate ()
        {       
            if (this.ajax.readyState != 4) return;
            if (this.ajax.status == 200)
            {
                // get our response
                var list = eval ('('+this.ajax.responseText+')');
    
                // compute milliseconds remaining till the end of the current song
                var start = new Date (list[0].date_played).getTime();
                var now   = new Date (                   ).getTime();
                var d = start - now
                      + parseInt(list[0].duration); // JSON data are plain strings, don't forget
                                                    //  to convert then to numbers if need be
                if (d < 0)
                {
                    // no new song started, retry in 10 seconds
                    d = 10000;
                }
                else
                {
                    // notify caller
                    this.onUpdate (list);
                }
    
                // schedule next refresh
                setTimeout (this.onSongEnd, d);
    
            }
            else
            {
                // Ajax request failed. Most likely a fatal error
                this.onError ("Bloody Ajax request failed");
            }       
        }
    }
    

    请注意,这是纯粹的,纯粹的JavaScript。这是教育代码,因此如果您有兴趣,可以使用它来查看使用匿名Ajax的示例。

    由于bind()的使用,它在IE8中不起作用,但如果您计划支持旧牛,则可以轻松添加包装函数。

    使用JQuery goo可以更容易地进行Ajax查询。我自己永远无法忍受这些东西,但毫无疑问,你会发现很多人都愿意向你展示它是如何完成的。

    用法

    var list = new PlayList (playlistupdate, playlisterror);
    
    function playlistupdate (list)
    {
        // do whatever you want with the playlist
        console.log ("Playlist update at "+new Date().toTimeString());
        for (var i = 0 ; i != list.length ; i++)
        {
            var song = list[i];
            console.log (i+" "+song.title);
        }
    }
    
    function playlisterror (msg)
    {
        // display error message
        console.log ("Ajax error: "+msg);
    
        // may want to retry, but chances of success are slim
        list.retry (10); // retry in 10 seconds
    }
    

    PHP(真实数据库访问)

    // make this query non cacheable
    /*
     * if you don't do this, your browser will cache
     * your first query and ignore the subsequent ones
     */
    header("Cache-Control: no-cache");
    
    // open your DB connection
    require_once("DbConnect.php");
    
    // fetch playlist
    $result = $db->query(
        "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`, `picture` "
       ."FROM historylist  ORDER BY `date_played` DESC LIMIT 5 ");
    
    // this little line replaces your bunch of code
    while ($row=$result->fetch_object()) $list[] = $row;
    
    // encode and send the result
    echo json_encode ($list);
    

    请注意no-cache标头。这是阻止浏览器缓存请求的最简洁方法。

    前面提到的JQuery goo将为您提供一个糟糕的解决方案,包括在查询后添加一些垃圾(即用playlist.php替换playlist.php?some_random_junk以强制浏览器将每个请求作为唯一处理,从而污染您的浏览器缓存没有充分理由)。

    由于您可以控制执行查询的PHP,因此可以更好地处理源代码中的问题。

    PHP(模拟)

    我写了一个快速&amp;肮脏的测试工具免除数据库

    // read our dummy DB
    if (file_exists ("playlist.txt"))
    {
        foreach (explode ("\n", file_get_contents ("playlist.txt")) as $i => $line)
        {
            $line = explode ('|', $line);
            foreach (array ('title', 'date_played', 'duration') as $k =>$f)
            {
                $db[$i]->$f = $line[$k];
            }
        }
    
        $last_ended = strtotime($db[count($db)-1]->date_played)
                        + $db[count($db)-1]->duration/1000;
    }
    else $last_ended = time();
    
    function song_name ()
    {
        return
            array_rand (array_flip(array("A", "Your", "Some", "This", "No"))). " ".
            array_rand (array_flip(array("beautiful", "weird", "delightful", "doomed", "pink"))). " ".
            array_rand (array_flip(array("love", "kiss", "baby", "monster", "dude", "car")));
    }
    
    // add a new dummy song to our DB if the last one has ended
    if ($last_ended <= time())
    {
        $changed = true;
        $db[] = array ("title" => song_name(), "date_played" => date("M d Y H:i:s", $last_ended), "duration" => rand(10,20)*1000);
    
            // store only the last 5 songs in the dummy DB
        $db = array_slice ($db, -5);
        foreach ($db as $k => $record)
        {
            $out[$k] = implode ('|', (array)$record);
        }
        file_put_contents ("playlist.txt", implode ("\n", $out));
    }
    
    // make this query non cacheable
    header("Cache-Control: no-cache");
    
    // get DB output
    $list = array_slice (array_reverse ($db), 0, 5);
    
    // encode and send it
    echo json_encode ($list);
    

    示例输出(来自浏览器控制台)

       Playlist update at 00:34:26 GMT+0100 (Paris, Madrid)
       0 Your doomed love
       1 Your doomed dude
       2 No beautiful kiss
       3 Some pink baby
       4 Your delightful car
       Playlist update at 00:34:38 GMT+0100 (Paris, Madrid)
       0 No doomed baby
       1 Your doomed love
       2 Your doomed dude
       3 No beautiful kiss
       4 Some pink baby
    

    您可以同时获取两个测试文件here 由于难以以可读的方式模拟Ajax请求,我没有做JSFiddle。

    实际HTML显示

    根据流行的请求,这里有一个示例代码,它在网页上显示某些内容,而不是简单地将列表抄送到控制台。

    您只需要更改playlistupdate这样的内容:

    function playlistupdate (list)
    {
        // display the playlist inside a table
    
        // table header
        var table = '<tr>';
        for (var j in list[0]) table += '<th>'+j+'</th>';
        table += '</tr>';
    
        // list items
        for (var i = 0 ; i != list.length ; i++)
        {
            table += '<tr>';
            for (var j in list[i])
            {
                table += '<td>'+list[i][j]+'</td>';
            }
            table += '</tr>';
        }
    
        // update table
        document.getElementById ('playlist').innerHTML = table;
    }
    

    您需要在HTML中的某个位置定义一个空表:

    <table id='playlist'></table>
    

答案 1 :(得分:0)

LIMIT 5更改为LIMIT 1或删除此。我认为您的代码具有多个数组并且这在此源中不可用!!!只是我想。我不是试试......
TEST1是php文件?
var arr更改为var arr = new Array();

通过Ajax发送信息并使用它......