在对视图进行Ajax调用后如何触发“如果条件”?

时间:2019-01-23 15:15:39

标签: django django-forms

我正在构建一个搜索栏,用于搜索数据库中的对象,如果搜索找到了一些匹配的对象,它将在html页面中显示这些对象而无需重新加载。但是在我触发Ajax调用并从数据库中获取元组之后,它们并没有在模板上呈现

因此,流程是这样的:我在搜索栏中搜索“苹果”,点击搜索按钮,然后将ajax调用触发到我的视图。之后,如果我在数据库中找到任何“苹果”,则将布尔值“ search_successful”设置为“ True”。然后,我将其传递到我首先触发ajax的模板。现在,我已成功获取数据,并且布尔值正确设置为“ True”。到现在为止,一切工作正常。但是在将上下文传递到我的模板后,如果 search_successful = True ,它不会触发 if条件,该条件将显示数据。所有这些都是通过ajax调用完成的,而无需重新加载页面。

这是如果条件,我希望在进行ajax调用以打印数据后可以使用该条件:

<form  id="search_object">
    {% csrf_token %}
    <input type="text" id="search_my_object" placeholder="Search Item" id="search_my_object" class="form-control" required="true" style="border-color:#f4511e;"/>
    <br>
    <input type="submit" value="SEARCH" class="btn btn-lg" style="border-color:#f4511e; background-color:Transparent; color:white; margin-left:47%;">
</form>

{% if search_successful is True %}
    # Just print the retrieved data passed in the context
{% endif %}

<script type="text/javascript">
    $(document).on('submit', '#search_object', function(e){
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '{% url 'daily_object_search' %}',
            data: {
               search_object_name: $('#search_my_object').val(),
               csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function(data){
                if(data == "true"){
                    alert('This Object is Present');
                }
                else if(data == "invalid_query"){
                    alert("Please enter a valid object to be searched");
                }
                else{
                    alert('This object is not present');
                }
            }

        });
    });

Views.py:

def daily_object_search(request):
    context = {'search_successful': False}
    if request.method == 'POST':
        object_name = request.POST['search_object_name']
        print("The query for search :", object_name)
        if len(object_name) <= 2:
            print("The length of the object name :", len(object_name))
            return HttpResponse('invalid_query')
        my_cursor = mydb.cursor()
        sql = "select * from education_fruits where tag = '" + object_name + "'"
        my_cursor.execute(sql)
        result = my_cursor.fetchall()
        print(result)
        if my_cursor.rowcount <= 0:
            print("No object found")
            return HttpResponse('false')
        context['search_successful'] = True
        # Just append the 'result' data in the context before sending it
    return HttpResponse('true', context)

我尝试在if条件下打印数据,但由于在浏览器控制台中出现了上述错误,因此将其删除: XML解析错误:语法错误位置:http://127.0.0.1:8000/login/daily_object_search 第1行,第1列。 我对ajax调用和模板的理解缺少什么吗?

1 个答案:

答案 0 :(得分:0)

真的必须是布尔值吗?如果没有,您可以这样做并比较字符串。

Views.py

context['search_successful'] = "true"

模板

{% if search_successful|stringformat:"i" == "true" %}
    # Do whatever
{% endif %}

# stringformat:"i", converts your template variable into String since you want to make sure that you're comparing two objects with the same type.
# You can also change the string, it doesn't have to be "true" you can use "found", "checked" etc.