【问题标题】:How to pass the context from a view and access the context data in javascript in Django?如何从视图传递上下文并在 Django 中访问 javascript 中的上下文数据?
【发布时间】:2023-03-13 08:41:01
【问题描述】:

我在 django 视图中的字典中传递一些数据,我想在我的 javascript 代码中访问字典数据以在我的 html 中显示数据。但是每当我打印传递的上下文时,它只会在我的控制台上打印“成功”,而不是实际数据。

这是我的字典结构: context['search_successful'] = "一些字符串" 在对视图进行 ajax 调用后,我将此字典传递给我的成功函数。目前我只是传递 HTTPResponse('true', context)。

在我的 javascript 代码中收集数据后,我只想打印我的上下文数据,这将在我的控制台上给出“一些字符串”,但每次都会成功。

这是我的看法:

def daily_object_search(request):
    context = {'search_successful': "No"}
    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'] = "Yess"
    return HttpResponse('true', context)

这是我的模板:

<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, context){
                if(data == "true"){
                    alert('This Object is Present');  
                    /* Print the context data by creating a html tag and appending the context information to a <h1> tag by doing document.id.innerHTML = context['search_successful']*/                                 
                    console.log(context);
                }
                else if(data == "invalid_query"){
                    alert("Please enter a valid object to be searched");
                }
                else{
                    alert('This object is not present');
                }
            }

        });
    });
</script>

控制台应该给我类似“search_successful:是”或“search_successful:否”的信息,但每次都会给我成功。请帮忙!提前致谢。

【问题讨论】:

    标签: django


    【解决方案1】:

    上下文字典可以传递给render (https://docs.djangoproject.com/en/2.1/topics/http/shortcuts/#render),我在文档https://docs.djangoproject.com/en/2.1/ref/request-response/#httpresponse-objectsHTTPResponse 中找不到上下文引用

    如果您想返回一个复杂的值,请在响应中返回一个 json 作为内容。 您将内容始终设置为true(硬编码),因此实际上不区分任何情况,我认为这没有用。

    我建议你使用状态码来区分各种情况,比如invalid_query,看起来像400 Bad Request,或者No object found,即404 Not Found。在这种情况下,您应该在 ajax 调用中使用错误处理程序来捕获此否定响应。

    如果您只喜欢使用成功处理程序,您可以使用这样的 json:

    { 
    'result': 'invalid_query'
    }
    

    所以如果你想要传递获取的元素,你可以在 json 中添加一个键

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-01
      • 2017-09-04
      • 2020-11-17
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多