簡體   English   中英

Django 多個 AJAX 查詢圖像

[英]Django multiple AJAX queries for images

我制作了一個用戶可以單擊的按鈕,它向后端 class 圖像發出 AJAX GET 請求。 響應是圖像 url。 我將 url 粘貼到圖像標簽中並將其顯示在模板上

模型.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)

我不知道要修改什么,它將查詢數據庫中的每個圖像。 有人可以解決我的問題嗎?

它返回唯一的第一個元素,因為您在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('<img src="' + response.image_query + '" width="300">') ,附加原始 html 可能會導致XSS攻擊,如果你不是完全確定response.image_query是安全的,不要這樣做。 (因為它是 url 它應該被轉義)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM