【问题标题】:Django multiple AJAX queries for imagesDjango对图像的多个AJAX查询
【发布时间】:2021-03-12 15:34:34
【问题描述】:

我制作了一个用户可以单击的按钮,它向后端类 Image 发出 AJAX GET 请求。响应是图像 url。我将 url 粘贴到图像标签中并显示在模板上

models.py

class Image(models.Model):
    img = models.ImageField()

views.py def ajax(请求): 从 django.http 导入 JsonResponse

if request.is_ajax():
    image = request.FILES.get('data')
    aaa = Image.objects.get(id=1)
    aaa = str(aaa.img.url)
    return JsonResponse({'image_query': aaa}, status=200)

return render(request, 'components/ajax.html')

AJAX(模板)

<button id="getData" class="btn btn-success">Get</button>
<div id="seconds"></div>

...

<script>
    $(document).ready(function () {
        $('#getData').click(function () {
            $.ajax({
                url: 'ajax',
                type: 'get',
                data: {
                    data: $(this).text()
                },
                success: function (response) {
                    $('#seconds').append('<img src="' + response.image_query + '" width="300">')
                }
            })
        })
    })
</script>

一切正常,图像渲染到模板!现在我不想查询 ID=1 的图像,我希望将所有图像提取到模板中。 我试图通过在views.py中添加一个for循环来做到这一点,但它只返回第一个元素。

if request.is_ajax():
    image = request.FILES.get('data')
    for i in range(1, 5):
        aaa = Image.objects.get(id=i)
        aaa = str(aaa.img.url)
        return JsonResponse({'image_query': aaa}, status=200)

我不知道要修改什么,它将查询数据库中的每个图像。有人可以解决我的问题吗?

【问题讨论】:

    标签: python jquery django ajax


    【解决方案1】:

    它返回唯一的第一个元素,因为您在 for 循环内返回,而是将 return 1 缩进放回,并将所有 url 放入数组中。

    ... # code you have above
    images = []
    for i in range(1, 5):
        aaa = Image.objects.get(id=i)
        images.append(aaa.img.url)) # append the url to the list
    return JsonResponse({'images': images}, status=200) # 1 indent back
    

    因此,您必须像这样更改您的 javascript 代码。

    const success = (response) => {
        // Loop through each of the links
        for (let i=0; i < response.image_query.length; i++) {
            $('#seconds').append('<img src="' + response.image_query[i] + '" width="300">')
        }
    }
    
    // ... Other code
    
    $.ajax({
        url: 'ajax',
        type: 'get',
        data: {
            data: $(this).text()
        },
        success: success,
    });
    

    还要小心$('#seconds').append('&lt;img src="' + response.image_query + '" width="300"&gt;'),附加原始html 可能会导致XSS 攻击,如果您不能完全确定response.image_query 是否安全,请不要这样做。 (因为是url所以应该转义)

    【讨论】:

    • 如果我这样做,我只会得到 for 循环的最后一个元素,所以在这种情况下只有 id=5 的元素
    • 是的,那是我的错,更新了答案。
    • 好吧,你把它放在一个列表中,谢谢它对我有用:)
    猜你喜欢
    • 2021-12-07
    • 2022-01-18
    • 2010-11-26
    • 1970-01-01
    • 2021-11-14
    • 2018-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多