from django.shortcuts import render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

from wagtail.wagtailcore.models import Page
from wagtail.wagtailsearch.models import Query


def search(request):
    search_query = request.GET.get('query', None)
    page = request.GET.get('page', 1)

    # Search
    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # Record hit
        query.add_hit()
    else:
        search_results = Page.objects.none()

    # Pagination
    paginator = Paginator(search_results, 10)
    try:
        search_results = paginator.page(page)
    except PageNotAnInteger:
        search_results = paginator.page(1)
    except EmptyPage:
        search_results = paginator.page(paginator.num_pages)

    return render(request, 'search/search.html', {
        'search_query': search_query,
        'search_results': search_results,
    })

@@ -1,40 +1,4 @@
-from django.shortcuts import render%0A
 from
@@ -65,16 +65,89 @@
 nInteger
+%0Afrom django.http import JsonResponse%0Afrom django.shortcuts import render
 %0A%0Afrom w
@@ -254,16 +254,58 @@
 quest):%0A
+    json = request.GET.get('json', False)%0A
     sear
@@ -911,50 +911,16 @@
   re
-turn render(request, 'search/search.html',
+sponse =
  %7B%0A 
@@ -1002,11 +1002,408 @@
 ts,%0A
-
     %7D
+%0A%0A    if json:%0A        response%5B'search_results'%5D = %5B%0A            dict(%0A                (attr, getattr(result.specific, attr))%0A                for attr in %5B'title', 'url'%5D%0A                if hasattr(result.specific, attr)%0A            ) for result in response%5B'search_results'%5D%0A        %5D%0A%0A        return JsonResponse(response)%0A    else:%0A        return render(request, 'search/search.html', response
 )%0A

Add support for returning search results as JSON.