Django simpleJSON jQuery.parseJSON 无效标签

发布于 2024-10-30 14:27:10 字数 3631 浏览 3 评论 0原文

我在 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。但我不知道如何解决这个问题。

有什么想法吗?

干杯

马克

I have the following view in 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")

and the following template

{% 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 %}

when the periodicalUpdater fires and does a get, it gets the json as a string from the view function, which means I can access it like a normal json structure. And when I try to do the jQuery.parseJSON firefox firebug throws an "invalid label" error. I've read in a few places that this can be because jquery is expecting is expecting JSONP instead of JSON. but im not sure how to fix this.

Any ideas?

Cheers

Mark

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

刘备忘录 2024-11-06 14:27:10

尝试:

...
$.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/

Try:

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

That should tell the ajax call to use jsonp instead.

Note: As a disclaimer, I haven't actually used this library but I investigated this because I'm interested in a jQuery auto-updater myself. Looking at the docs here:

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

we can see that it uses the regular jQuery Ajax call and you can specify parameters to PeriodicalUpdater that then get passed into the Ajax call. The type field in PeriodicalUpdater appears to be equivalent to the dataType field in the jQuery ajax call whose docs are found here:

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文