【问题标题】:Django simpleJSON jQuery.parseJSON invalid labelDjango simpleJSON jQuery.parseJSON 无效标签
【发布时间】:2011-07-31 12:48:48
【问题描述】:

我在django中有如下视图

def playingNow(request,playlist_id):
    from django.db import connection
    cursor = connection.cursor()

    sql =   "SELECT id, timestamp, song_played_id, playlist_from_id, now() - timestamp as timepassed FROM music_song_played \n"\
            "WHERE playlist_from_id = %s \n"\
            "ORDER by timepassed ASC \n"\
            "LIMIT 1;"
    cursor.execute(sql,[playlist_id])
    data = cursor.fetchall()
    songPlaying = get_object_or_404(song, id = data[0][2])
    playing = {}
    playing["song"] = unicode(songPlaying)
    playing["licensed"] = "Licensed by "
    return HttpResponse(simplejson.dumps(playing), content_type ="application/javascript; charset=utf8")

和下面的模板

{% block content %}

<script type='text/javascript' src='/media/inthebackground-utils.js'></script>
<script type='text/javascript' src='/media/jwplayer/swfobject.js'></script>
<script type='text/javascript' src='/media/jwplayer/jwplayer.min.js'></script>
<script type='text/javascript' src='http://code.jquery.com/jquery-latest.pack.js'></script>
<script type='text/javascript' src='/media/jquery.periodicalupdater.js'></script>
<script type="text/javascript">
  var data = new Object();
</script>


  <div id="StationName">Your Listening to: {{ station.name }} </div>
  <div id="playingNow-{{ station.name }}"></div>
  <div id='padder{{ station.name }}' style="height:20px; float left"></div>
  <div id='mediaspace-{{ station.name }}'"><p> You dont have adobe flash player installed. Please download and install from <a href="http://get.adobe.com/flashplayer">here</a> </div>

  <script type="text/javascript">

    data.{{ station.name }} = {'userid':'{{ user.pk }}', 'playlist' : '{{ station.pk }}'};

    $.PeriodicalUpdater('/music/playingNow/{{ station.pk }}/',
                    {method: 'get'}, 
                    function(remoteData, success, xhr, handle)
                    {

                      jQuery.parseJSON(remoteData);
                      console.log(typeof(remoteData));
                      console.log(remoteData);
                      licenceDiv = '<div id="licence">'+remoteData.license +'</div>';
                      songDiv = '<div id="licence">'+remoteData.song +'</div>';
                      contDiv = '<div id="playingNow-{{ station.name }}">' + songDiv + licenceDiv +'</div>';
                      $('#playingNow-{{ station.name }}').replaceWith(contDiv);
                      jwplayer('mediaspace-{{ station.name }}').play(true);
                     });

    jwplayer('mediaspace-{{ station.name }}').setup({
      flashplayer: "/media/jwplayer/player.swf",
      file: "{{ station.url }}?{{ cacheBuster }}",
      height: 20,
      width: 300,
      controlbar: "bottom",
      provider: "sound",
      duration: "0",
      events: {
        onPlay: function(event){play(data.{{ station.name }});},
        onPause: function(event){pause(data.{{ station.name }});}
        }
     });

     $(window).unload( function () { pause(data.{{ station.name }} ); } );
  </script>


{% endblock %}

当periodicalUpdater 触发并执行get 时,它会从视图函数中获取json 作为字符串,这意味着我可以像普通的json 结构一样访问它。当我尝试执行 jQuery.parseJSON firefox firebug 时会抛出“无效标签”错误。我在几个地方读到这可能是因为 jquery 期望的是 JSONP 而不是 JSON。但我不确定如何解决这个问题。

有什么想法吗?

干杯

标记

【问题讨论】:

    标签: javascript jquery django json simplejson


    【解决方案1】:

    试试:

    ...
    $.PeriodicalUpdater('/music/playingNow/{{ station.pk }}/',
                    {method: 'get',
                     type: 'jsonp'}, 
                    function(remoteData, success, xhr, handle) ...
    

    这应该告诉 ajax 调用使用 jsonp。

    注意:作为免责声明,我实际上并没有使用过这个库,但我对此进行了调查,因为我自己对 jQuery 自动更新程序很感兴趣。查看此处的文档:

    https://github.com/RobertFischer/JQuery-PeriodicalUpdater/

    我们可以看到它使用常规的 jQuery Ajax 调用,您可以为 PeriodicalUpdater 指定参数,然后将其传递给 Ajax 调用。 PeriodicalUpdater 中的 type 字段似乎等同于 jQuery ajax 调用中的 dataType 字段,其文档可在此处找到:

    http://api.jquery.com/jQuery.ajax/

    【讨论】:

    • 干杯我会检查出来。附带说明一下,虽然我还没有在愤怒中使用 PeriodicalUpdater,但到目前为止它在 dev 中运行良好。我还没有看到有多少负载来自大量客户端,但总体而言,这似乎是一个相当不错的实现。
    • 试一试,不幸的是这并没有解决问题。我仍然收到无效标签错误。
    • 服务器返回的数据是什么样的?使用 jsonp,我相信它应该作为一个有效的 javascript 对象返回,你甚至不需要解析它。有关类似问题,请参阅此线程:stackoverflow.com/questions/3543513/…
    猜你喜欢
    • 1970-01-01
    • 2012-05-17
    • 2011-07-18
    • 2016-01-26
    • 2015-02-10
    • 2011-12-01
    • 2014-08-18
    • 2016-04-12
    • 2012-03-09
    相关资源
    最近更新 更多