我可以使用预设变量放置一个json调用字符串吗?

时间:2013-06-27 22:59:00

标签: javascript jquery json for-loop

<?php
date_default_timezone_set('America/Los_Angeles');
$time = date('Gi', time());
$day = date('l', time());
?>

<script type="text/javascript">
$(function() {
  $(".show_hide").click( function()
       {
        var locTime = <?php echo json_encode($time) ?>;
        var locDate = <?php echo json_encode($day) ?>;

$.getJSON( "url_to_json", function(data) {
    for (var i = 0; i < data.location[locDate].length; i++) { 
    console.log("sucess1");
    xr_mon= data.location.locDate[i];
    console.log("sucess2");
     if (locTime >= xr_mon.kai && locTime < xr_mon.guan ){
        console.log("cafe is open!");
        $('.xr').show(); 
        break;
        }


    else {
        console.log("cafe is closed");
        $('.xr').hide();
    }
    }
});
       }
  );
});

JSON

{ "location": 
{
    "Monday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100}
    ],

    "Tuesday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100}
    ],

    "Wednesday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100},
    {"kai": 2200, "guan": 2400},
    {"kai": 0, "guan": 200}
    ],

    "Thursday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100},
    {"kai": 2200, "guan": 2400},
    {"kai": 0, "guan": 200}
    ],

    "Friday": [
    {"kai": 700, "guan": 1400},
    {"kai": 1700, "guan": 2100},
    {"kai": 2200, "guan": 2400},
    {"kai": 0, "guan": 200}
    ],

    "Saturday": [
    {"kai": 1000, "guan": 1500},
    {"kai": 1700, "guan": 2100},
    {"kai": 2200, "guan": 2400},
    {"kai": 0, "guan": 200}
    ],

    "Sunday": [
    {"kai": 1000, "guan": 1500},
    {"kai": 1700, "guan": 2100},
    {"kai": 2200, "guan": 2400},
    {"kai": 0, "guan": 200}
    ]
}
}

其中kai =开放时间 和guan =关闭时间

带有locDate的

是通过php服务器端日期提取的,我想用我的JSON调用字符串替换生成的日期,该字符串包含工作日的部分。

来自这个

  for (var i = 0; i < data.location.'locDate'.length; i++)

到这个

  for (var i = 0; i < data.location.Thursday.length; i++)

我该如何以正确的方式做到这一点。有人建议使用[locDate],但它不会替换php日期数据中的变量。

1 个答案:

答案 0 :(得分:2)

使用括号表示法。

for (var i = 0; i < data.location[locDate].length; i++)

另一个例子:

thing = [1, 2, 3, 4, 5]
//The following lines do the same thing:
thing.pop()
thing['pop']()