【问题标题】:Search with ajax + django view使用 ajax + django 视图搜索
【发布时间】:2018-08-14 09:43:11
【问题描述】:

你能帮帮我吗?我想使用 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})

【问题讨论】:

  • print(data) 给你什么?
  • @hansTheFranz &lt;QueryDict: {}&gt; - 第一行 &lt;QueryDict: {'search_by': ['qwer asdf zxcv'], 'csrfmiddlewaretoken': ['svfwfyu2sxUmNkI9byPHNuTmYkOKU5LBoDSP8rNsicn7LN5bJKFS9r1LUNdDIvyZ']}&gt; - 第二行。但是在其他任何地方都没有打印功能。我检查所有视图
  • 您需要查找如何从 json 格式的数据中获取值。我猜“qwer asdf zxcv”是您在搜索栏中输入的内容?例如stackoverflow.com/questions/44598962/…
  • @hansTheFranz 是的,它是我在搜索栏中输入的。但在另一种观点中,我做了同样的事情,一切都很好

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


【解决方案1】:
  $.ajax({
        url: '/search-products/',
        data: {
          'search_by': q
        },
        dataType: 'json',
        success: function (data) {
            // do your thing
        }
      });

【讨论】:

  • 从数据发送中删除 csrf 令牌并将 ajax 函数中的数据更改为 data: {'search_by': q} 并将获取数据的视图更改为 search_by = request.GET.get('search_by')。它没有帮助。
  • 尝试直接将查询作为数据传入,而不是使用字典
  • 你能告诉我我是怎么做的吗?我不知道
  • 虽然此代码可以回答问题,但提供有关 如何为什么 解决问题的附加上下文将提高​​答案的长期价值。
猜你喜欢
  • 2013-08-13
  • 1970-01-01
  • 1970-01-01
  • 2018-05-02
  • 2016-10-07
  • 2018-07-11
  • 2014-10-07
  • 2012-05-15
  • 1970-01-01
相关资源
最近更新 更多