在javascript变量

时间:2017-01-31 10:10:48

标签: javascript php mysql date

我有这个代码非常有效。但我想用mysql。

以下是有效的代码:

<?php if (date('w') == 2) { { ?>
<script> $(function() {
var times = [
// mysql import start
{'id': '1', 'name': 'Mardi 5H55', 'end': new Date('2017-01-31 05:55:00'),},
{'id': '2', 'name': 'Mardi 8H40', 'end': new Date('2017-01-31 08:40:00'),},
{'id': '3', 'name': 'Mardi 11H30', 'end': new Date('2017-01-31 11:30:00'),},
{'id': '4', 'name': 'Mardi 14H05', 'end': new Date('2017-01-31 14:05:00'),}
// mysql import end
];
        // Initialize the table values
        $.each(times, function( key, value ) {
            $('#mau-mpl').append('<tr><td>'+value.name+'</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-'+value.id+'-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
        });
        function countdown()
        {
            var now = new Date();
            console.log('updating time');

            $.each(times, function( key, value ) {
                var left = value.end - now;
                var days = Math.floor( left / (1000 * 60 * 60 * 24) );
                var hours = Math.floor( (left % (1000 * 60 * 60 * 24) ) / (1000 * 60 * 60) );
                var minutes = Math.floor( (left % (1000 * 60 * 60)) / (1000 * 60) );
                var seconds = Math.floor( (left % (1000 * 60)) / 1000 );

                displayTime = '';
                if (days > 0) {
                    displayTime = + days + " jr   ";
                }
if (minutes > 0) {
                displayTime = displayTime + hours + " H   " + minutes + " Mn   "  + seconds + " Sec   ";
} 
                echo = "Deja parti"; 


                $('#player-'+value.id+'-expiration').text(displayTime)
            });
        }
        timer = setInterval(countdown, 1000);        
    });</script><?php } } ?>

如您所见,我想要的数据是在 mysql import start 之后。 我制作了一个从mysql中获取数据的php文件,我得到了这个结果:

  • {&#39; id&#39;:&#39; 1&#39;,&#39; name&#39;:&#39; Mardi 5H&#39;,&#39; end&#39;:新日期(&#39; 2017-01-31 05:00:00&#39;),},
  • {&#39; id&#39;:&#39; 2&#39;,&#39; name&#39;:&#39; Mardi 6H&#39;,&#39; end&#39;:新日期(&#39; 2017-01-31 06:00:00&#39;),},
  • {&#39; id&#39;:&#39; 3&#39;,&#39; name&#39;:&#39; Mardi 7H&#39;,&#39; end&#39;:新日期(&#39; 2017-01-31 07:00:00&#39;),},

php文件是:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "horaires";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$sql = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
// {'id': '1', 'name': '5H', 'end': new Date('2017-01-31, 05:55:00'),},";
echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
} $conn->close();
?>  

+---+----------+---------------------+
| 1 | Mardi 5H | 2017-01-31 05:00:00 |
+---+----------+---------------------+
| 2 | Mardi 6H | 2017-01-31 06:00:00 |
+---+----------+---------------------+
| 3 | Mardi 7H | 2017-01-31 07:00:00 |
+---+----------+---------------------+

如何将结果放在&#34; mysql import start&#34;之间的javascript变量中?和&#34; mysql导入结束&#34; ?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

var js = <?php echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "')}"; ?>

但警告,我最后删除了你对象上的坏字符:

echo "{'id': '" . $row["id"]. "', 'name': '" . $row['name'] ."', 'end': new Date('" . $row["jourheure"]. "" . $row["depart"]. "'),},<br>"; }
---------------------------------------------------------------------------------------------------------------------------------^-^^^^^

答案 1 :(得分:0)

你可以用很多不同的方式设置var,ajax,在php代码中嵌入javascript代码......

如果你想获得一个PHP对象或var到javascript你需要在php代码中将对象序列化为JSON,那么你需要设置你的JSON字符串并将这个字符串转换为一个有效的javascript对象。

JSON是这样的字符串

"{'propertyname':'stringvalue','property2':true,'property3':null,'property':[...]}" 

如果现在你可以在javascript代码块上解析JSON

的index.php

<?php 
   $result = getData() // your data like you want =>[ multiple objects ]
   $resultJSON =  json_encode($result); // "[{..},{...}]"
?>
<script>
    var jsondata = parse.JSON('<?php echo $resultJSON ?>') ; 
</script>

但我认为最好从php代码中分割html / javascript代码,例如从ajax获取变量。

答案 2 :(得分:0)

您可以使用AJAX调用PHP脚本将数据存储到Javascript变量中。

在以下文件中,演示了使用JQuery的AJAX调用将数据存储到Javascript

<?php if (date('w') == 2) { { ?>
<script>
        $(function() {
            var times = $.ajax({
                url: 'api.php', //the script to call to get data          
                data: "", //you can insert url argumnets here to pass to api.php
                //for example "id=5&parent=6"
                dataType: 'json', //data format      
                success: function(data) //on recieve of reply
                {
                    return data;
                }
            });
            $.each(times, function(key, value) {
                $('#mau-mpl').append('<tr><td>' + value.name + '</td><td>Hérault Transports (Ruban Bleu)</td><td>Montpellier</td><td><span id="player-' + value.id + '-expiration" class="label label-primary">Chargement encours...</span></td></tr>');
            });

            function countdown() {
                var now = new Date();
                console.log('updating time');
                $.each(times, function(key, value) {
                    var left = value.end - now;
                    var days = Math.floor(left / (1000 * 60 * 60 * 24));
                    var hours = Math.floor((left % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    var minutes = Math.floor((left % (1000 * 60 * 60)) / (1000 * 60));
                    var seconds = Math.floor((left % (1000 * 60)) / 1000);
                    displayTime = '';
                    if (days > 0) {
                        displayTime = +days + " jr   ";
                    }
                    if (minutes > 0) {
                        displayTime = displayTime + hours + " H   " + minutes + " Mn   " + seconds + " Sec   ";
                    }
                    echo = "Deja parti";
                    $('#player-' + value.id + '-expiration').text(displayTime)
                });
            }
            timer = setInterval(countdown, 1000);
        });
    });</script><?php } } ?>

以下是从数据库中提取数据的代码 我们称这个文件为api。

<?php
$servername = "localhost";
$username   = "root";
$password   = "root";
$dbname     = "horaires";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
$sql    = "SELECT id, jourheure, name, depart, arrivee FROM 2_mardi";
$result = $conn->query($sql);
if ($result->num_rows > 0) {

    //storing result into an array
    $array = mysql_fetch_row($result);
}
$conn->close();

//encoding the array into JSON
echo json_encode($array);
?>