-1

我已经编辑了这个问题以反映下面的答案。

数组 $animation 是从另一个函数编码返回的,包含 URL 字符串,如 index.html、index1.html 等。

我使用此功能生成动画..

$select = "SELECT card_id, order_num FROM decks WHERE box_num=$box_num AND id=$userid ORDER BY order_num";
    $result = mysqli_query($db, $select) or die("SQL Error 1: " . mysqli_error($db));

    while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
        $animation[] = array(
            'card_id' => $row['card_id'],
            'order_num' => $row['order_num'],
        );
    }

    return json_encode($animation);

$animation 的内容是

"[{"card_id":"baby","order_num":"1"},{"card_id":"selectBaby","order_num":"2"},{"card_id":"bed","order_num" :"3"},{"card_id":"selectBed","order_num":"4"},{"card_id":"book","order_num":"5"},{"card_id":"selectBook" ,"order_num":"6"},{"card_id":"cup","order_num":"7"},{"card_id":"selectCup","order_num":"8"},{"card_id" :"cupboard","order_num":"9"},{"card_id":"selectCupboard","order_num":"10"},{"card_id":"daddy","order_num":"11"},{"card_id":"selectDaddy","order_num":"12"},{"card_id":"eating","order_num":"13"},{"card_id":"mummy"," order_num":"14"},{"card_id":"selectMummy","order_num":"15"},{"card_id":"plate","order_num":"16"},{"card_id":" selectPlate","order_num":"17"},{"card_id":"shoe","order_num":"18"},{"card_id":"selectShoe","order_num":"19"},{" card_id":"table","order_num":"20"},{"card_id":"selectTable","order_num":"21"},{"card_id":"walking","order_num":"22"},{"card_id":"selectWalking","order_num":"23"},{"card_id":"dogNose","order_num":"24"},{"card_id":" selectDogNose","order_num":"25"},{"card_id":"teddyEars","order_num":"26"},{"card_id":"selectTeddyEars","order_num":"27"},{" card_id":"ActivityOne","order_num":"28"},{"card_id":"ActivityTwo","order_num":"29"},{"card_id":"ActivityThree","order_num":"30" },{"card_id":"ActivityFour","order_num":"31"},{"card_id":"ActivityFive","order_num":"32"},{"card_id":"ActivitySix","order_num":"33"}]"

然后我尝试将它传递给javascript。

var url = <?php echo $animation; ?>;
alert(url); //check the for some data

这段代码的输出是

对象 对象 对象 对象 对象 对象 对象 对象 对象 对象 对象 对象

我需要的输出是 card_id,所以我可以将它传递给 url,例如:baby、bed、book 等

网址 网址 网址 网址

我需要字符串来做到这一点..

$(document).ready(function() {
   var suffix = ".html";
   $('#buffer').load('../Animations/' + url[0] + suffix);
   $('#buffer').trigger('create');    
});
4

3 回答 3

2

您似乎没有在任何地方创建 JSON。除非$animation已经是 JSON 字符串,否则您需要这样做:

var jsonUrl = <?php echo json_encode($animation); ?>;
于 2013-06-13T13:34:30.733 回答
2

我假设你有一个有效的json我认为你可以json_decode用来将你的 json 解码为一个数组。此函数还支持第三个参数,如果给定为 true,则将您的 json 作为关联数组返回。

请在这里阅读更多

于 2013-06-13T13:34:43.327 回答
1
  • 首先,检查<?php echo $animation; ?>输出是否为有效的 json 字符串。
  • 其次,JSON.parse并非所有浏览器都支持,您应该使用类似$.parseJSON(来自 jquery)的库

在您的情况下,如果您不输出",则根本不需要JSON.parse,因为该对象已经是一个 javascript 对象。示例:如果<?php echo $animation; ?>被渲染成类似的东西{x:1,y:2},你渲染的 javascript 看起来像这样

var jsonUrl = {x:1,y:2};

它已经是一个 javascript 对象

于 2013-06-13T13:35:05.550 回答