javascript - 通过 Ajax 从 Django 连续获取图像

标签 javascript jquery python ajax django

我正在使用 Django 创建一个非常非常简单的应用程序,允许客户端通过正常请求发布图像。然而,查看实际网页的用户会在其中运行 Javascript,执行连续的 AJAX 请求来查找其他客户端发布的下一张图片,但在 django 服务器上本地查看它们。即本地客户端打开页面,js不断提交ajax帖子寻找1号图片。当远程客户端发布1号图片时,本地客户端在网页中看到1号图片,然后不断向服务器请求2号图片……等等。

下面是响应本地客户端ajax的 View :

class ViewPictures(View):

def post(self,request):


    #look for ajax request
    if request.is_ajax():

        req_post = request.POST

        #the pk of the picture the client is looking for
        num_pic = req_post["pk"]




        #get the picture from SQL
        try:

            picture = Picture.objects.get(pk=num_pic)


        except Picture.DoesNotExist:
            data = simplejson.dumps({'picture':0})

            return HttpResponse(data,content_type="application/json")


        #get the local path of the pic

        path = picture.photo.file

        #Serialize pathname
        response_data = simplejson.dumps({'picture':str(path)})

        #response with path name JSON

        return HttpResponse(response_data,content_type="application/json")
    else:
        #else forbidden request
        return HttpResponseForbidden()

这是本地客户端的客户端页面:

    function get_pic(pic_num){

    //ajax request for pic   
    $.ajax({
        url:'{% url "viewpics"%}',
        method: 'POST',
        async: true,
        data: {'pk':pic_num},   
        success: function(response){

            //if pic not none
            if(response.picture!=0){
                var image = '<img id="image" src='+response.picture+ ' height="42" width="42" />'; 
                $(".image_show").prepend(image);
                pic_num++;
            }
            get_pic(pic_num);

        },
        error: function(jqXHR, textStatus, errorThrown){
            alert(errorThrown);
        }


    });


};
$(document).ready(get_pic(1));
</script>
<head>
    <title>IMAGE VIEWER</title>
    <div class ="image_show">
    </div>

</head>

我读到,由于服务器与获取图片的客户端位于同一台计算机上,因此将本地计算机上的图片路径发送到客户端是有意义的。但是,我还了解到浏览器不允许本地访问 html 页面中的文件。我想知道是否有一种方法允许客户端在其网页中查看本地imgs,或者是否更好地序列化本地imgs并将它们发送给客户端?有没有更好的方法来做到这一点,应该在两个客户端都远程的情况下完成吗?

最佳答案

可以通过客户端浏览器访问本地文件系统。 这可以使用 html5 来完成。 请参阅以下文档:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader https://developer.mozilla.org/en/Using_files_from_web_applications

请注意,旧版浏览器不支持此方法。

最常用的解决方案是将图像上传到服务器并返回服务器图像 URL。这可能更容易实现,并且旧浏览器也支持。这就是我推荐的。

关于javascript - 通过 Ajax 从 Django 连续获取图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33288221/

相关文章:

javascript - AngularJS ng-show动画在ng-repeat中交叉淡入淡出

Javascript 只允许数字粘贴

php - 将 json 数组从 PHP 传递到 JS

jquery - 理解这行 jQuery

python - 使用 Python 和 SQLite3 动态生成 SQL 查询

python - JSON SCHEMA PATTERN逗号分隔列表

javascript - 如何获取 url 参数并添加事件类 witt javascript/jquery?

javascript - 如何使用 Google Doubleclick API 检查特定插槽是否已加载?

python - 你如何测试两个字典是否与python中的pytest相等

javascript - JS 正则表达式 : Wrap content in multiple tags defined in appended lines?