动态更新从AJAX查询返回的JSON数组

时间:2015-08-18 03:45:52

标签: javascript php jquery arrays json

我正在查询我为我的网站制作的API,它以这种格式返回数据:

{
   "success":true,
   "code":1,
   "quantity":3,
   "classes":[
      [
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lab",
            "days":"W",
            "times":"09:00 am - 10:50 am",
            "crn":"11216"
         },
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lecture",
            "days":"T",
            "times":"02:00 pm - 03:20 pm",
            "crn":"11215"
         },
         {
            "name":"ECEC 302 Digital Systems Projects Lab",
            "days":"MW",
            "times":"03:00 pm - 04:50 pm",
            "crn":"12567"
         }
      ],
      [
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lab",
            "days":"W",
            "times":"09:00 am - 10:50 am",
            "crn":"11216"
         },
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lecture",
            "days":"T",
            "times":"02:00 pm - 03:20 pm",
            "crn":"11215"
         },
         {
            "name":"ECEC 302 Digital Systems Projects Lab",
            "days":"TR",
            "times":"09:00 am - 10:50 am",
            "crn":"13523"
         }
      ],
      [
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lab",
            "days":"F",
            "times":"02:00 pm - 03:50 pm",
            "crn":"11217"
         },
         {
            "name":"ECEC 301 Advanced Programming for Engineers Lecture",
            "days":"T",
            "times":"02:00 pm - 03:20 pm",
            "crn":"11215"
         },
         {
            "name":"ECEC 302 Digital Systems Projects Lab",
            "days":"MW",
            "times":"03:00 pm - 04:50 pm",
            "crn":"12567"
         }
      ],
   "message":"3 schedule[s] were generated"
}

当页面加载时,面板会像这样查询此API:

    $.ajax({
        url: '{{ URL('schedulizer/schedules') }}',
        type: "GET",
        dataType: 'json'
    }).done(function(data){
        // Get the hash
        window.location.hash = '#1';
        var type = window.location.hash.substr(1);
        $("#classes").html(JSON.stringify(data.classes[type]));
    });

它的作用是,它获取URL哈希(例如#1),并将其用作JSON API中classes数组的索引。查询可能包含许多计划,或根本没有计划。

我有一些测试HTML,它们本质上是具有与当前哈希值不同的哈希值的按钮。我试图看看我是否可以遍历JSON数组的不同索引:

<div class="panel panel-primary">
    <div class="panel-heading">
        <h3 class="panel-title">Schedule</h3>
    </div>
    <div id="classes" class="panel-body panel-options">
        <div class="btn-group">
            <a href='{{ URL('schedulizer/schedule#2') }}' class="btn btn-default"><</a>
            <a href='{{ URL('schedulizer/schedule#3') }}' class="btn btn-default">></a>
        </div>
    </div>
</div>

页面看起来像这样。如您所见,有一个JSON数组的索引和按钮。

enter image description here

问题:

当我点击该按钮时,我发现网址哈希从#1更改为#2更改为#3,但是,我没有看到JSON更改。

classes对象返回的数据是数组数组。我想使用按钮循环遍历这些数组数组而不重新加载页面,然后更新#classes

我对Javascript和异步编程都很陌生,所以非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

你刚刚离开了一步:

  1. 在您当前发布的结构中,$("#classes").html(JSON.stringify(data.classes[type]));会覆盖您的按钮,这会让您的按钮消失,您应该将它们移动到其他位置。

  2. 将响应数据保存在另一个变量中,并在单击时根据功能添加eventListener到button,增加或减少要显示的index,并使用{{如前所述,为了显示数据,请记住将响应数据和我提到的索引保持在点击处理程序中。

  3. 所以你可以像这样写代码:

    .html

    演示时间为jsfiddle。请注意,jsfiddle将代码包装在var result; var index = 0; $.ajax({ url: '{{ URL('schedulizer/schedules') }}', type: "GET", dataType: 'json' }).done(function(data){ // Get the hash window.location.hash = '#' + (index + 1); // Save the response data to hash result = data; $("#classes").html(JSON.stringify(result.classes[index])); }); $('.btn.btn-default').click(function(e) { // Prevent the page redirect to another page, as you have href on it. // Or you can remove the href on the anchors. e.preventDefault(); // Prevent undesired behaviors happen when data is not retrieved yet. if (!result || !result.classes) { return; } // Calculate next index for data to show. // I use the text < or > here to check, better way may be add class left/right to each anchor. var next = $(this).text() === '<' ? -1 : 1; index = index + next; // Make the index in boundary. if (index >= result.classes.length) { index = 0; } else if (index < 0) { index = result.classes.length - 1; } // Add hash. window.location.hash = '#' + (index + 1); $("#classes").html(JSON.stringify(result.classes[index])); }); 回调中,建议您执行此操作,使用window.onloaddomready来包装代码。