使用ajax + django视图搜索

时间:2018-03-06 13:51:01

标签: jquery ajax django django-templates django-views

你可以帮助我吗?我想使用ajax函数和django视图创建搜索。有输入和提交按钮。当我点击提交按钮时,jQuery获取输入值并创建ajax请求。很好。但在视图中,当我想在控制台中打印serch_by值时,有一个输出:

None qwer asdf zxvc< - 输入值

我认为这是一个问题。但也许没有。请帮帮我。

HTML:

<form id="searchform" {% csrf_token %}
  <input name="q" type="text" id="search">
  <button type="submit" id="searchsubmit"></button>
</form>

JS:

function initSearchForm(){
    $('#searchsubmit').on('click', function(e){
        e.preventDefault();
        q = $('#search').val();
        updateContentBySearch(q);
  });
}
function updateContentBySearch(q) {
    var data = {};
    data['search_by'] = q
    data["csrfmiddlewaretoken"] = $('#searchform [name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: "/search_products/",
        type: 'GET',
        data: data,
        success:
            $('.product_content').load(url, function() { ...
            }),
        });

    }

查看:

def search_products(request):
     data = request.GET
     search_by = data.get('search_by')
     print(search_by) # The console is displayed first 'None' and at 
                      # the next line value of search_by
if search_by:
    q = Q()
    for tag in search_by.split():
        q |= Q(brand__brand_name__iexact=tag) | Q(model__iexact=tag)
    products = Product.objects.filter(q)

return render(request, 'main/product_content.html', {'products': product})

1 个答案:

答案 0 :(得分:0)

  $.ajax({
        url: '/search-products/',
        data: {
          'search_by': q
        },
        dataType: 'json',
        success: function (data) {
            // do your thing
        }
      });