简体   繁体   English

Javascript,Mysqli和PHP循环

[英]Javascript, Mysqli, and PHP Looping

I am working on a site, and I am having to create a PHP loop with Javascript in it. 我正在一个网站上工作,并且必须在其中创建一个包含Javascript的PHP循环。 Is this possible? 这可能吗? Here is the snippet of code I need looped. 这是我需要循环的代码片段。

<? while($calendar = mysqli_fetch_array($client_get_calendar)) { ?>
{
 title: '<? echo $calendar['event_title'] ?>',
 start: new Date(<? echo date("Y", strtotime($calendar['date_start'])) ?>, <? echo date("m", strtotime($calendar['date_start'])) ?>, <? echo date("d", strtotime($calendar['date_start'])) ?>),
 end: new Date(<? echo date("Y", strtotime($calendar['date_end'])) ?>, <? echo date("m", strtotime($calendar['date_end'])) ?>, <? echo date("d", strtotime($calendar['date_end'])) ?>),
 className: '<? echo $calendar['importance'] ?>'
},
<? } ?>

Will this work for what I am trying to accomplish? 这会为我想要完成的工作吗? It gives me an error, but I don't know what is wrong with the code. 它给了我一个错误,但是我不知道代码有什么问题。 Thanks for any help! 谢谢你的帮助!

You appear to be building JSON output for a Javascript object of data. 您似乎正在为数​​据的Javascript对象构建JSON输出。

This would be better achieved with the following. 这将通过以下方法更好地实现。

<?php
$calendar = mysqli_fetch_array($client_get_calendar);
echo json_encode($calendar);
?>

Modify the array as you like in a loop. 根据需要循环修改数组。

JSON is good, JSON don't kill Arctic Bears. JSON很好, JSON不会杀死北极熊。 Everytime someone build a Javascript object without JSON an Arctic Bear dies. 每当有人构建没有JSON的Javascript对象时,北极熊都会死亡。

$rows = array();
while($calendar = mysqli_fetch_array($client_get_calendar)) {
    $nRow = array(
        'title'     => '' /* <= do your tricks here */,
        'start'     => '' /* <= and here  */,
        'end'       => '' /* <= and here  */,
        'className' => '' /* <= and here  */
    );
    // Now append it do rows
    $rows[] = $nRow;
} 
// dat magic
echo json_encode($rows);

I assume you get a syntax error at IE. 我假设您在IE上收到语法错误。

And you are trying to make a javascript array of object. 而且您正在尝试制作对象的javascript数组。

In this case, you got an extra comma at the end of the script and that will cause error on IE. 在这种情况下,脚本末尾会出现一个逗号,这将导致IE错误。 the solution is just like @IAmNotProcrastinating said, make a json. 解决方案就像@IAmNotProcrastinating所说的,制作一个json。

so as the answer above, you can save your data and encode it into a json string. 因此,作为上述答案,您可以保存数据并将其编码为json字符串。

Continue @IAmNotProcrastinating work, instead of direct output: 继续@IAmNotProcrastinating工作,而不是直接输出:

<?php
if(count($row)>0){
    $data = json_encode($row);
}
else{
    $data = json_encode(array());
}
?>
var js_data = <?php echo $data; ?>;
do_something_with_js_data(js_data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM