JSONP不在HTML表格中显示数据

时间:2014-06-30 13:54:43

标签: javascript php mysql ajax json

这是我的PHP页面,位于我的虚构域http://www.myradiostation1.localhost(测试域,不可通过Web访问)。它与http://www.vikingfm.co.uk/on-air/station-schedule/类似,但不一样 - 并且是我自己的CSS更改样式表/网站设计更改的测试副本

  <link rel="stylesheet" type="text/css" href="index.css" media="all">
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <div class="content-inner">
                                              <div class="row">
          <div class="column size-10">
          <div class="large-schedule-widget main-col main-col-large widgetbox">
                     <table class="schedule-table">
                <!-- column headers -->
                <thead>
                    <tr>
                        <th class="hide">Units</th>
                        <th>Hours</th>
                        <th>Monday</th>
                        <th class="active">Tuesday</th>
                        <th>Wednesday</th>
                        <th>Thursday</th>
                        <th>Friday</th>
                        <th>Saturday</th>
                        <th>Sunday</th>
                    </tr>
                </thead>
                <tbody>

                    <tr id="units-0">
                        <td class="hide">0</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">00:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>
                    <tr id="units-1">
                        <td class="hide">1</td>
                        <!-- Every other row echo an hour block -->
                    </tr>

                    <!-- echo a row for each of the 48 units -->
                    <tr id="units-2">
                        <td class="hide">2</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">01:00</td>
                        <!-- start polling days -->

                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-3">
                        <td class="hide">3</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->                 
                    </tr>

                    <tr id="units-4">
                        <td class="hide">4</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">02:00</td>

                    <tr id="units-5">
                        <td class="hide">5</td>
                        <!-- start polling days -->

                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-6">
                        <td class="hide">6</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">03:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-7">
                        <td class="hide">7</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-8">
                        <td class="hide">8</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">04:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-9">
                        <td class="hide">9</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-10">
                        <td class="hide">10</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">05:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-11">
                        <td class="hide">11</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-12">
                        <td class="hide">12</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">06:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-13">
                        <td class="hide">13</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-14">
                        <td class="hide">14</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">07:00</td>
                        <!-- start polling days -->
                    <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-15">
                        <td class="hide">15</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-16">
                        <td class="hide">16</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">08:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-17">
                        <td class="hide">17</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-18">
                        <td class="hide">18</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">09:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-19">
                        <td class="hide">19</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-20">
                        <td class="hide">20</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time current_time" rowspan="2">10:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-21">
                        <td class="hide">21</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-22">
                        <td class="hide">22</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">11:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-23">
                        <td class="hide">23</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-24"> 
                        <td class="hide">24</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">12:00</td>
                        <!-- start polling days -->
                        </tr>

                    <tr id="units-25">
                        <td class="hide">25</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-26">
                        <td class="hide">26</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">13:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                        </tr>

                    <tr id="units-27">
                        <td class="hide">27</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-28">
                        <td class="hide">28</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">14:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                        </tr>

                    <tr id="units-29">
                        <td class="hide">29</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-30">
                        <td class="hide">30</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">15:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-31">
                        <td class="hide">31</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-32">
                        <td class="hide">32</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">16:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-33">
                        <td class="hide">33</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-34">
                        <td class="hide">34</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">17:00</td> 
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-35">
                        <td class="hide">35</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-36">
                        <td class="hide">36</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">18:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-37">
                        <td class="hide">37</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-38">
                        <td class="hide">38</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">19:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-39">
                        <td class="hide">39</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-40">
                        <td class="hide">40</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">20:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-41">
                        <td class="hide">41</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-42">
                        <td class="hide">42</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">21:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-43">
                        <td class="hide">43</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-44">
                        <td class="hide">44</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">22:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-45">
                        <td class="hide">45</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-46">
                        <td class="hide">46</td>
                        <!-- Every other row echo an hour block -->
                        <td class="time" rowspan="2">23:00</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-47">
                        <td class="hide">47</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>

                    <tr id="units-48">
                        <td class="hide">48</td>
                        <!-- start polling days -->
                        <!-- finish echo a row for each of the 48 units -->
                    </tr>                   


                </tbody>
            </table>
</div> <!-- end .main-col -->
<script>
var doFades = true;

var MyLocalhostStations = {
  Schedule : {}
};

$(document).ready(function(){

  MyLocalhostStations.Schedule.days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

  MyLocalhostStations.Schedule.Show = function () {
    _s = null;
    _startDate = null;
    _endDate = null;
    this.days = MyLocalhostStations.Schedule.days;
    _selector = '';

    this.setShow = function(s) {
      this._s = s;

      this._startDate = new Date( parseInt(s.startminutes, 10) * 1000);
      this._endDate = new Date(parseInt(s.endminutes, 10) * 1000 ); 

    };

    this.getEndDate = function(){
      return this._endDate;
    }

    this.getStartDate = function(){ 
      return this._startDate;
    }

    this._getShowDay = function (){
      return this.days[this.getStartDate().getDay()];
    };

    this._getShowUnitsTaken = function(){
      // if it's the same day
      return this._getEndUnits() - this._getStartUnits();
    };

    this._getEndUnits = function(){   
      if(this.getEndDate().getHours() == 0)
      {
        //console.log(this._s.longname  +' ends at midnight');
        return 48;
      }

      return this.getEndDate().getMinutes() !== 0 ? (this.getEndDate().getHours() * 2) : (this.getEndDate().getHours() * 2);
    };

    this._getStartUnits = function(){
      if(this.getStartDate().getHours() == 0)
      {
        return 0;
      }

      return this.getStartDate().getMinutes() !== 0 ? (this.getStartDate().getHours() * 2) : (this.getStartDate().getHours() * 2);
    };

    this.getCellPositions = function() {
      return {
        'start' : this.getStartDate(),
        'end' : this.getEndDate(),
        'colIndex' : this.getStartDate().getDay() + 2,
        'startUnits' : this._getStartUnits(),
        'endUnits' : this._getEndUnits(),
        'unitsTaken' : this._getShowUnitsTaken()
      }
    };

    this.pad = function(number){
      return number < 10 ? '0'+number : number; 
    };

    // return the table cell html.
    this.toHtml = function () {

      var d = new Date();
      var units = this._getStartUnits();

      var rowspan = this._getShowUnitsTaken();    
      var desc = this._s.description;
      var name = this._s.longname;

      var starttime   = this.pad(this.getStartDate().getHours()) + ':' + this.pad(this.getStartDate().getMinutes());
      var endtime   = this.pad(this.getEndDate().getHours()) + ':' + this.pad(this.getEndDate().getMinutes());

      var site = this._s.websitelink;

      var cls = this.isActive() ? 'current-program' : '';

      var isToday = this.getStartDate().getDay() === d.getDay() ? 'active-program' : '';

      var html = '<td class="schedule-show ' + isToday + ' ' + cls + '" rowspan="' + rowspan + '" data-start="' + this.getStartDate() + '" data-end="' + this.getEndDate() + '">';
        html += '<div>';
        html += '<a href="' + site + '" title="' + desc + '">' + name + '</a>';
        html += '</div>';
        if(doFades)
        {
          html += '<div class="schedule_details clearfix" style="display:none;">';
          html += '<img width="105px" height="105px" alt="' + desc + '" src="' + this._s.showimage + '">';
          html += '<strong>' + name + '</strong>';
          html += '<p>' + desc + '</p>';
          html += '<span>' + starttime + ' - ' + endtime +'</span>';
          html += '</div>';
        }
        html += '</td>';      

      return html;
    };

    this.setTableSelector = function(sel){
      this._selector = sel;
    };

    // check if we should add the active class.
    this.isActive = function(){
      var t = new Date();

      return  t >= this.getStartDate() && t <= this.getEndDate();
    };
  };

  MyLocalhostStations.Schedule.ScheduleGen = function(){

    return {
      insertShow : function(show) {
        var p = show.getCellPositions();

        $('tr#units-' + p.startUnits).append(show.toHtml());
      },

      init : function (stationName){
        var self = this;

        // load the schedule.
        $.getJSON('http://www.myradiostation2.localhost/schedule.php?callback=?', {
          name: 'North FM'
        }, function(json){
          // loop each show and append to our giant table.
          // this is well sick.

          if(json.success === false)
          {
            $('.content-inner table').remove();

            $('<div>errors</div>').appendTo('.content-inner');
          }
          else
          {
            var currentDay = '';
            var day = 0;
            // highlight the current time..
            var d = new Date();
            var weekStart = new Date();

            weekStart.setDate(d.getDate()-6-(d.getDay()||7));

            $.each(json.data.schedule, function(i, broadcast){


              var dStart = new Date( parseInt(broadcast.startminutes, 10) * 1000);
              var dEnd = new Date(parseInt(broadcast.endminutes, 10) * 1000 ); 


              /*// transform to a show object defined above, if the show spans 2 days we create two show objects.
              // IF THE SHOW STARTS/ENDS AT MIDNIGHT, DON'T SPLIT IT.
              if(dStart.getHours() !== 0 && dEnd.getHours() !== 0 && dStart.getDate() != dEnd.getDate())
              {
                var showOne = new MyLocalhostStations.Schedule.Show();
                showOne.setShow(broadcast);

                // set to midnight 
                showOne.getEndDate().setHours(0);
                showOne.getEndDate().setMinutes(dStart.getMinutes());


                // append first half of show.
                self.insertShow(showOne);

                // handle second half.
                var showTwo = new MyLocalhostStations.Schedule.Show();
                showTwo.setShow(broadcast);

                showTwo.getStartDate().setDate(showTwo.getStartDate().getDate() + 1);
                showTwo.getStartDate().setHours(0);
                showTwo.getStartDate().setMinutes(dEnd.getMinutes());

                //console.log('2nd Half Start: ' + showTwo.getStartDate());
                //console.log('2nd Half End: ' + showTwo.getEndDate());

                self.insertShow(showTwo);


              }
              else
              {*/
                var show = new MyLocalhostStations.Schedule.Show();

                show.setShow(broadcast);
                show.setTableSelector('table#schedule');

                // add the show to the table. Thankfully the order these come out the API means they get added 
                // in the right place. So don't change the schedule builder code!

                self.insertShow(show);
              //}


            });

            var days = MyLocalhostStations.Schedule.days;   

            // apply the current day / time classes 
            $('th:contains('+ days[d.getDay()]+')').addClass('active');

            $('td.time').each(function(i, cell){
              // get the value, convert to int. 
              var hours = $(cell).html().split(':')[0];

              // compare the hours with now, add class if matched. 
              if(parseInt(hours, 10) === d.getHours())
              {
                $(cell).addClass('current_time');
              }
            });
          }


          if(doFades)
          {
            // apply events to show info fade in / out.
            $('td.schedule-show').hover(function(){
              $(this).find('.schedule_details').fadeIn('fast');
            }, function(){
              $(this).find('.schedule_details').fadeOut('fast');
            });
          }
        });


      }
    };
  }();


  MyLocalhostStations.Schedule.ScheduleGen.init(twittiName);

});
</script>

和我在http://www.myradiostation2.localhost/schedule.php?callback=?&name=North+FM的JSONP代码:

    <?php
   header('Content-type: application/javascript;');
header("access-control-allow-origin: *");
header("Access-Control-Allow-Methods: GET");
  //db connection detils
  $host = "localhost";
  $user = "test";
  $password = "test";
  $database = "myradiostation1";

  //make connection
  $server = mysql_connect($host, $user, $password);
  $connection = mysql_select_db($database, $server);

  //query the database
  $query = mysql_query("SELECT *, DATE_FORMAT(start, '%d/%m/%Y %H:%i:%s') AS start, 
                                   DATE_FORMAT(end, '%d/%m/%Y %H:%i:%s') AS end FROM radiostation1");

    //loop through and return results
  for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
    $row = mysql_fetch_assoc($query);

    $shows[$x] = array("id" => $row["id"], "startminutes" => $row["startminutes"], "start" => $row["start"], "endminutes" => $row["endminutes"],"end" => $row["end"],"mediumname" => $row["mediumname"], "longname" => $row["longname"], "description" => $row["description"],"short_id" => $row["short_id"],"promomessage" => $row["promomessage"],"email" => $row["email"],"phonenumber" => $row["phonenumber"],"textnumber" => $row["textnumber"],"textprefix" => $row["textprefix"],"showimage" => $row["showimage"],"longdescription" => $row["longdescription"],"facebooklink" => $row["facebooklink"],"otherlink" => $row["otherlink"],"websitelink" => $row["websitelink"],"keywords" => $row["keywords"] );     
  }

  //echo JSON to page
  $response = $_GET["callback"] . "(" . json_encode($shows) . ");";
  echo $response; 

JSONP有效,但我的代码没有显示在HTML表格中。

为什么我的表格空白而且没有显示代码?

3 个答案:

答案 0 :(得分:2)

PHP中的数据结构只是一个数组:

$foo = array(
  0 => array(... data from row #1 of the query),
  1 => array(... data from row #2 of the query),
  etc...
);

以JSON格式,

[{..row1 data..},{..row2 data..},....,{..row n data..}]

在该结构中,您没有success密钥或data密钥。因此,您的JS代码中不存在json.datajson.success也不存在。

如果你想要那种结构,你必须这样做:

$foo = array(
   'success' => true,
   'data' => array()
);

然后

while ($row = mysql_fetch_assoc($result)) {
   $foo['data'][] = $row;
       ^^^^^^^^---- you don't have this.
}

echo $_GET['callback'] . "(" . json_encode($foo) . ")";

答案 1 :(得分:0)

您要返回的JSON是一个数组,它没有data属性,因此json.data.schedule会出错。

答案 2 :(得分:0)

很难理解你的代码,因为你有很多东西,我的建议是尝试用ajax请求做一个简单的页面,用一个“for”看看发生了什么,并使用一些调试工具,并使用的console.log。

实施例

 <script>
 $.getJSON('http://www.myradiostation2.localhost/schedule.php?callback=?', {
      name: 'North FM'
    }, function(json){
       console.log(json);
       for(var key in json){
       console.log("********"+key+"*********");
       console.log(json[key]);
       }
       });
 </script>

通过这种方式,您可以查看所有内容是否与您的请求一致,如果您的脚本中有一个良好的逻辑,那么您可以获取该对象并尝试查看创建html是否正常工作等等。 / p>

我知道这不是最好的答案,但是调试代码的方法之一。

为什么你使用jsonp?今天通常你可以使用简单的json。