【问题标题】:MySQL/PHP Array to JavascriptMySQL/PHP 数组到 Javascript
【发布时间】:2013-04-06 17:10:18
【问题描述】:

所以我想将我所有的 MySQL 结果存储在一个可以用 javascript/jQuery 操作的数组中。

这是我当前的代码:

<?php
    $sql = "SELECT * FROM potentials";
    $result = mysql_query($sql) or die(mysql_error());
    $potential = mysql_fetch_array($result);
    echo json_encode($potential);
?>

还有我的 Javascript:

<script type="text/javascript">
    $(document).ready(function(){
        var myArray = "<?php print(json_encode($potential)); ?>";
        console.log(myArray)
    )};
</script>

我不断收到“意外号码”或“意外标识符”。怎么回事?

【问题讨论】:

  • 它的回声很好,但没有在 javascript 中显示 console.log。

标签: php mysql arrays json


【解决方案1】:

你使用了两次json_encode(),但是如果你想使用它,你需要解析它。在 jQuery 中,这可以像这样通过jQuery.parseJSON 完成

var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');

此外,如果您想要所有结果,则需要循环查询(例如使用while),然后将其保存到数组中

$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
    $array[] = $row;
}

【讨论】:

  • 这在控制台中给了我这个:Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON'
【解决方案2】:
<script>
    var data = '<?php echo $data; ?>';
    var json = JSON.parse(data);
    console.log(json[0]); //etc
</script>

请注意 var data = ... 是单引号,因此您将 php 的回显作为字符串捕获

【讨论】:

    【解决方案3】:

    json_encode() 使用 JSON 表示法返回一个对象。奇怪的是,你用引号包围了它。尝试删除它们:

    <script type="text/javascript">
    $(document).ready(function(){
        var myArray = <?php print(json_encode($potential)); ?>;
        console.log(myArray);
    });
    </script>
    

    (它不是一个数组,它是一个对象,所以你可能想要重命名你的变量;))

    【讨论】:

    • 它现在只吐出第一行潜力。如何获取所有行?多维数组?那会是什么样子?也许是一个 foreach 语句?
    • 我会选择这样的: $(document).ready(function(){ var myArray = "' . json_encode($potential) . '"; console.log(myArray) )}; 脚本>' 。 "\n"; ?>
    • 注:替换 )};和 });在答案的第 5 行,以防止控制台中出现“意外令牌”错误。
    猜你喜欢
    • 2023-03-05
    • 2016-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2014-03-30
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多