使用表单和Django后端更新页面

时间:2018-09-20 00:18:12

标签: javascript python jquery ajax django

我正在开发一个由前端HTML / JS / CSS和Django / Python后端提供服务的Web应用程序。我的目标是根据用户的一些输入实时更新前端页面,并将其转换为HTML形式,然后以jQuery ajax形式传递给后端。此时,后端将处理在表单中传递的数据,然后将新数据返回到jQuery请求,从那里可以编辑页面而无需重新加载。

但是,当我尝试执行此操作时,页面将重定向到我的帖子URL。如何在不导致页面重新加载或重定向的情况下将数据从后端传递回前端。

这是到目前为止我的代码:

前端jQuery ajax形式:

$('#InputForm').on('submit', function(event){
    event.preventDefault();
    console.log("form submitted!")
    $.ajax({
        url : "/friendData/", // the endpoint
        type : "POST", // http method
        data : { friend : $('#FriendInput').val(), csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val() }, // data sent with the post request

        // handle a successful response
        success : function(json) {
            $('#FriendInput').val(''); // remove the value from the input
            console.log(json); // log the returned json to the console
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
});

Views.py文件:

def friendData(request):
    if request.method == "POST":
        return JsonResponse({"result": "works"}, content_type="application/json", safe=False)
    else:
        return JsonResponse(
                {"nothing to see", "this not happening"}, content_type="application/json")

和URLS.py

urlpatterns = [
    path('friendData/',views.friendData, name='friendData')
]

HTML表单:

<form action="friendData/" method="POST" id="InputForm">
                {% csrf_token %}
                <div class="form-group">
                    <label for="FriendInput">Friend name</label>
                    <input type='text' class="form-control" id="FriendInput" aria-describedby="FriendHelp" placeholder="Friend">
                    <small id="FriendHelp" class="form-text text-muted">Input the Friend's name</small>
                </div>
            </form>

每当我提交表单时,我都会重定向到localhost:8000 / friendData,它只是显示json响应。我该如何将json响应发送回ajax请求,在此我可以处理它并在不刷新的情况下操作索引页面,而不是移至一个新页面。

0 个答案:

没有答案