L
L
lleviy2019-11-26 11:18:29
JavaScript
lleviy, 2019-11-26 11:18:29

How to correctly return an array from views to a template with an AJAX request?

I have the following ajax function that reads the value of the input field and sends it to the view, in the view I form an array of urls from this value and want to return it back to the template. The function correctly reads the value, view also forms the array correctly.
The problems start when the array is displayed in the template. My view returns in the div id="results" field not only an array, but the entire html page. It turns out a page within a page. And this is logical, because in the view I really pass the entire new_topic.html template - I don't know how it is possible to pass only one array.

$(function(){
    $("#search_btn").click(function () {
        q = $( "#search" ).val();
        if (q!=''){
            var s = 'search_photos/'
            $.get(s, {'q': q}).done(function (data) {

                $( '#results').html(data);

            });
        }
    });
});


views.py:

def search_photos(request):
    if request.method == 'GET':
        q = request.GET.get('q')
        photos_url = []
        #Здесь формирую массив photos_url
            return render(request, 'myapp/new_topic.html', {'photos_url':photos_url})
    return render(request, 'myapp/new_topic.html', {})


new_topic.html:

<input id="search" name="q" type="text" class="form-control" placeholder="Поиск">
 <input name='submit_s' id='search_btn' type='button' value='poisk' />
    <div id="results"> Сюда хочу вывести обработанный список url-ов </div>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Shatalov, 2019-11-26
@lleviy

from django.http import JsonResponse
def search_photos(request):
    if request.method == 'GET':
        q = request.GET.get('q')
        photos_url = []
        #Здесь формирую массив photos_url
        return JsonResponse(photos_url)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question