JSONP和GET与回调 - 帮助需要更正错误 [英] JSONP and GET with callbacks - help needed correcting errors

查看:224
本文介绍了JSONP和GET与回调 - 帮助需要更正错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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 = 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);

//循环并返回结果
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], text row=> $ row [text] => $ text [textprefix=> $ row [textprefix],showimage=> $ row [showimage],longdescription=> facebooklink],otherlink=> $ row [otherlink],websitelink=> $ row [websitelink],keywords=> $ row [keywords]);
}

// echo JSON到页面
$ response = $ _GET [callback]。 (。json_encode($ shows)。);;
echo $ response;

?>

它有效, success:true,error:,data:{schedule:这个网站之前我的json_encode是我的地方。



但是,我不能让它显示任何数据表,虽然它在屏幕上产生代码,当我在 https://www.myradio1.localhost/ onairschedule.php



实际代码存储在 http://www.myradiostations.localhost/schedule.php



并且回调函数工作正常,一个示例为 http://www.myradiostations.localhost/schedule.php?callback =?& ; name = Northern + FM http:/ /www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM ,但是我需要做些什么来使它改变,就像这些例子:
此示例此示例,并生成错误消息,如如果没有此类文件,则为此





基本上,我想要做的...获取一个JSONP在我的HTML表中工作,这将是根据我的网页上的JavaScript文件中的网址更改内容,即:

  var doFades = true; 

var LocalhostRadioStations = {
Schedule:{}
};

$(document).ready(function(){

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

LocalhostRadioStations.Schedule.Show = function(){
_s = null;
_startDate = null;
_endDate = null;
this.days = LocalhostRadioStations.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(){
//如果是同一天
return this。 _getEndUnits() - this._getStartUnits();
};

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

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

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

返回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 $ b'unitsTaken':this._getShowUnitsTaken()
}
};

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

//返回表单元格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 =' getStartDate()+'data-end ='+ this.getEndDate()+'>';
html + ='< div>';
html + ='< a href ='+ site +'title ='+ desc +'>'+ name +'< / a>'
html + ='< / div>';
if(doFades)
{
html + ='< div class =schedule_details clearfixstyle =display:none;>';
html + ='< img width =105pxheight =105pxalt ='+ 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;
};

//检查我们是否应该添加活动类。
this.isActive = function(){
var t = new Date();

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

LocalhostRadioStations.Schedule.ScheduleGen = function(){

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

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

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

//加载计划。
$ .getJSON('http://www.myradiostations.localhost/schedule.php?callback =?& name =',{
name:'Northern FM'
},function (json){
//循环每个节目并附加到我们的巨型表
//这很好病了

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

$('< div> errors< / div>')appendTo('。 content-inner');
}
else
{
var currentDay ='';
var day = 0;
//突出显示当前时间..
var d = new Date();
var weekStart = new Date();

weekStart.setDate(d.getDate() - 6- ()|| 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);


/ * //转换为上面定义的显示对象,如果显示跨越2天,我们创建两个显示对象。
//如果显示开始/结束在中午,不要分割。
if(dStart.getHours()!== 0& dEnd.getHours()!== 0&& dStart.getDate()!= dEnd.getDate())
{
var showOne = new LocalhostRadioStations.Schedule.Show();
showOne.setShow(broadcast);

//设置为午夜
showOne.getEndDate()。setHours(0);
showOne.getEndDate()。setMinutes(dStart.getMinutes());


//追加显示的前半部分。
self.insertShow(showOne);

//处理下半部分。
var showTwo = new LocalhostRadioStations.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 LocalhostRadioStations.Schedule.Show();

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

//将显示添加到表中。幸运的是,这些出来的顺序API意味着他们在正确的地方添加
//。所以不要改变计划生成器代码!

self.insertShow(show);
//}


});

var days = LocalhostRadioStations.Schedule.days;

//应用当前日期/时间类
$('th:contains('+ days [d.getDay()] +')')。addClass('active') ;

$('td.time')。每个函数(i,cell){
//获取值,转换为int
var hours = $ ).html()。split(':')[0];

//比较小时和现在,如果匹配,添加class
if(parseInt(hours,10) == d.getHours())
{
$(cell).addClass('current_time');
}
}
}


if(doFades)
{
//应用事件来显示信息淡入/淡出。
$('td.schedule-show')。hover(function(){
$(this).find('schedule_details')。fadeIn('fast');
} ,function(){
$(this).find('。schedule_details')。fadeOut('fast');
});
}
});


}
};
}();


LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);

});

它应该根据JSONP改变计划,但是我该怎么做来解决它? p>

基本上,我想让我自己的localhost版本 http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM 及其JSON / JSONP(我不确定是什么类型原始的是,但是然后又是站点是实验和在.localhost域)为测试目的,其中内容是从数据库取得,并根据站名称,例如, http://radioplayer.bauerradio.com/schedule.php?callback =& name = Metro +电台 http: //radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One 等。



编辑:我的网页的完整代码可在 http://pastebin.com/ENhR6Q9j 中查看

解决方案

我不知道到底是什么缺失,但从你给的代码到目前为止,我做了一个jsfiddle:



演示



我修改了一些内容使它工作(主要是附加的东西),因为我不知道你原来的HTML文件。但我也根据你说的话做了一些修改。首先我修改你的 $。getJSON 调用是类似:

  $ .getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?',{
name:stationName // stationName来自传递的参数
},function( json){...})

这应该根据传递给

  LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName); 

为了更有趣,我还添加了一些从url读取的代码。在这种情况下,如果您转到具有 domain.htm / page?Northern FM 的页面,它将读取并将其放在 twittiName

  var twittiName =摇滚FM; //默认站

if(window.location.search){
twittiName = window.location.search.substring(1)//或window.location.hash
}

试图寻找可能在您的公共网站上的其他电台,但到目前为止,我只能测试与→Rock + FM。但是确实意味着你可以显示你的代码可以处理的错误,因为它是。





所以看起来你的代码大部分都可以工作,但如果我错过了任何东西都会发表评论。


This is my JSONP file:

<?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; 

?>

It does work, up to a point, but getting the {"success":true,"error":"","data":{"schedule": as seen at this site before my json_encode is where I am.

However, I cannot get it to display any data in my table, although it DOES produce code on-screen when I view it at http://www.myradio1.localhost/onairschedule.php.

The actual code is stored at http://www.myradiostations.localhost/schedule.php

and the callback function works OK, one example being http://www.myradiostations.localhost/schedule.php?callback=?&name=Northern+FM and http://www.myradiostations.localhost/schedule.php?callback=?&name=Southern+FM but what do I need to do to make it change like in these examples: this example and this example, and to generate an error message like this if no such file exists.

I'm halfway there, just need some advice on fixing my code!

Basically, what I'm trying to do... get a JSONP to work in my HTML table which will vary the content depending on the URL in my javascript file on my page, which is:

var doFades = true;

var LocalhostRadioStations = {
  Schedule : {}
};

$(document).ready(function(){

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

  LocalhostRadioStations.Schedule.Show = function () {
    _s = null;
    _startDate = null;
    _endDate = null;
    this.days = LocalhostRadioStations.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();
    };
  };

  LocalhostRadioStations.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.myradiostations.localhost/schedule.php?callback=?&name=', {
          name: 'Northern 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 LocalhostRadioStations.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 LocalhostRadioStations.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 LocalhostRadioStations.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 = LocalhostRadioStations.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');
            });
          }
        });


      }
    };
  }();


  LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);

});

It should change the schedule according to the JSONP, but what do I do to fix it?

Basically, I am trying to make my own localhost version of http://radioplayer.bauerradio.com/schedule.php?callback=&name=Rock+FM and its JSON / JSONP (I am not sure exactly what type the original is, but then again the site is experimental and on a .localhost domain) for testing purposes where the content is taken from the database, and changes according to station name, e.g. http://radioplayer.bauerradio.com/schedule.php?callback=&name=Metro+Radio and http://radioplayer.bauerradio.com/schedule.php?callback=&name=Forth+One etc.

Edit: The full code for my page can be seen at http://pastebin.com/ENhR6Q9j

解决方案

I'm not sure exactly what's missing, but from the code you gave so far, I made a jsfiddle:

Demo

I modified some things to make it work (mostly appending stuff), because I don't know your original HTML file. But I also made some changes based on what you say you wanted. First of all I modified your $.getJSON call to be something like:

$.getJSON('http://radioplayer.bauerradio.com/schedule.php?callback=?', {
          name: stationName //stationName is from the argument passed
        }, function(json){...})

Which should give back the station based on what is passed to

LocalhostRadioStations.Schedule.ScheduleGen.init(twittiName);

To make it more interesting, I also added a bit of code that reads from the url. In this case if you go to the page with a domain.htm/page?Northern FM it will read the text after the ? and put it in twittiName.

var twittiName="Rock FM"; //default station

if(window.location.search){
   twittiName=window.location.search.substring(1)   //or window.location.hash
}

Tried to look for other stations that might be on your publics site, but so far I could only test with "?Rock+FM". But does mean you can show the errors, which your code can handle as it is.

So it seems that your code mostly works but do comment if I have missed anything.

这篇关于JSONP和GET与回调 - 帮助需要更正错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆