gpt4 book ai didi

javascript - JSON 编码的 PHP 数组到 JAVASCRIPT 变量

转载 作者:行者123 更新时间:2023-11-29 13:17:52 25 4
gpt4 key购买 nike

请有人告诉我如何将我创建并输出到jsondata.php的以下结果放入JavaScript中的变量中,以便我可以索引 通过结果并在整个网站的 Div 中使用它们。

所需变量是:

$lastplayed 中的所有内容以及 $secsemain 的结果

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

测试1

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

最佳答案

首先,您不想仅仅为了获取当前歌曲的剩余时间而对 PHP 脚本生成连续的请求。最好让 JavaScript 来处理这个问题。

你的 JavaScript 必须决定两件事:

  1. 何时获取下一批歌曲描述
  2. 如何获取它

可能的解决方案是:

让你的 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);

注意无缓存 header 。这是防止浏览器缓存您的请求的最干净的方法。

前面提到的 JQuery goo 将为您提供一个糟糕的解决方案,包括在查询后面添加一些垃圾(即用 playlist.php?some_random_junk 替换 playlist.php 来强制浏览器将每个请求视为唯一的,从而无缘无故地污染您的浏览器缓存)。

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

PHP(模拟)

我编写了一个快速而肮脏的测试工具来省去数据库

// 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>

关于javascript - JSON 编码的 PHP 数组到 JAVASCRIPT 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21242366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com