使用ajax / javascript将django响应渲染到同一页面

时间:2014-04-30 08:51:22

标签: javascript ajax django

我有一个页面通过谷歌API绘制Youtube视频的缩略图,我使用Masonry来控制所述缩略图&单击时放大元素(此时我想让iframe显示视频)。

我想要做的是渲染一个包含iframe和amp;的模板。缩略图元素中所选视频的一些额外内容。麻烦的是,我在一个例子中没有明确找到的javascript我不是很好!

目前为非脚本用户设置了django ......

我的缩略图页面位于/videos/,每个缩略图都呈现以下模板;

<div class="video">
    <a class="GetYoutubeVideo" data-video-id="{{ object.video_id }}" href="{% url 'show_video' video_id=object.id %}">
    {{ object.get_img_tag }}
    <span class="title">
        <p>{{ object.get_title|slice:":20" }}...</p>
        <p class="date">{{ object.date_created|date:"d/m/Y" }}</p>
    </span>
    </a>
</div>

<script>
    $(document).ready(function(){
        $(".GetYoutubeVideo").click(function(){
            $.ajax({
                type: "POST",
                dataType: 'json',
                url: $(this).attr('href'),
                timeout: 5000,
                data: {
                    csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
                    video_id: $(this).attr('data-video-id')
                },
                success : function(json) {
                    console.log('Success ' + json);
                    $('#result').append('Server Response: ' + json.server_response);
                },
                error : function(xhr, errmsg, err) {
                    // Currently hits this with an empty `err`
                    console.log('Ajax Error: ' + errmsg + ' and ' + err);
                    alert(xhr.status + ": " + xhr.responseText);
                }
            })
        })
    });
</script>

使用以下视图在/videos/<video_id>/处使用视频iframe;

@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
    """
    Displays the selected YouTube video.

    @type request:      HttpRequest
    @param request:     The HttpRequest object
    @type page_id:      int
    @param page_id:     The ID of the page where this video is found
    @type video_id:     int
    @param video_id:    The id of the video to display the images of
    @rtype:             HttpResponse
    @return:            The rendered template
    """
    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return render_to_response('display_video.html',
        RequestContext(
            request, {
                'page_id': page_id,
                'video': video,
                'video_data': video_data,
            }
        )
    )

我是否需要执行类似操作,例如将点击事件绑定到包含$.ajax的缩略图链接,然后在request.is_ajax()中设置show_video()

修改 这是我在$.ajax()中遇到错误回调时的观点:

@csrf_exempt
@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):

    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return HttpResponse(
        json.dumps({
            'page_id': page_id,
            'video': serializers.serialize('json', [video, ]),
            'video_data': video_data,
        }), content_type="application/json"
    )

2 个答案:

答案 0 :(得分:1)

试试这个,

<div class="video">
    <a class="GrapSomeData" href="{% url 'show_video' video_id=object.id %}">{{ object.get_img_tag }}
    <span class="title">
        <p>{{ object.get_title|slice:":20" }}...</p>
        <p class="date">{{ object.date_created|date:"d/m/Y" }}</p>
    </span>
    </a>
</div>

Django观点:

@never_cache
def show_video(request, page_id=None, video_id=None, **kwargs):
    """
    Displays the selected YouTube video.

    @type request:      HttpRequest
    @param request:     The HttpRequest object
    @type page_id:      int
    @param page_id:     The ID of the page where this video is found
    @type video_id:     int
    @param video_id:    The id of the video to display the images of
    @rtype:             HttpResponse
    @return:            The rendered template
    """
    # Get the VideoGalleryPlugin object
    video = get_object_or_404(VideoGalleryPlugin, pk=video_id)
    video_data = video.video_data()

    return HttpResponse(json.dumps({
                'page_id': page_id,
                'video': video,
                'video_data': video_data,
            }))

在Jquery方面,

$(document).ready(function(){
   $(".GrapSomeData").click(function(){
      $.ajax({
        type:"GET",
        dataType: 'json',
        url:this.href,
        success: function(response){
           // Get response from django server
          // do your code here
        }
      })
   })
});

答案 1 :(得分:1)

如果您没有在同一方法中使用多个操作,则实际上不需要添加request.is_ajax()。如果您只想在ajax调用中加载页面,那么使用代码就可以了。

按照jquery ajax代码,

jQuery(function(){
jQuery('class_or_id').on('click', function(){
  jQuery.ajax(
    url: 'your_url',
    type: 'POST or GET',
    success: function(response){
      //whatever you want
      // means if you want to load your content in specific place you can
    }
  );
});
});

我希望你会喜欢:)