简体   繁体   English

如何使用jQuery将数据发送到Django视图并呈现Django模板?

[英]How to send Data with jQuery to Django view and render the Django template?

I have some data in javascript and want to send it to a Django view function. 我在javascript中有一些数据,希望将其发送到Django视图函数。 After that I want to render a Django template using HttpResponse, but how it works? 之后,我想使用HttpResponse渲染Django模板,但是它如何工作?

First I had send some data to a Django view with jQuery.ajax() and used the response data, now I want to send data within a second jQuery.ajax() - after a button was clicked - to a different Django view function and finally render a simple template, like how it works, if I click a simple link on a website. 首先,我已经使用jQuery.ajax()将一些数据发送到Django视图,并使用了响应数据,现在我想在第二个jQuery.ajax()中(单击按钮后)将数据发送到另一个Django视图函数,然后如果我单击网站上的简单链接,则最终呈现一个简单的模板,如模板的工作方式。

I have cut the snippet as far as possible for the sake of clarity 为了清楚起见,我已尽可能减少了代码段

$(matchfield).on('click', function(event) {
    event.preventDefault();
    var field = $(this).val();
    $.ajax({
        method: "POST",
        url: "/view-function/",
        data: { "field": field },
        dataType: "json",
        context: this,
        success: function (data) {
            if(data.message === 1) {
                points = 100
                $('#submit').on('click', function(event) {
                    event.preventDefault();
                    $.ajax({
                        url: "/another-view/",
                        method: "POST",
                        data: {"points": points},
                        success:function(response){ // I guess the mistake is here
                            $(document).html(response) 
                        }
                    })
                })
            }
        }
    });
});

If the #submit Button was clicked, The status code of the Response is 200 and Chrome Dev Tools shows the complete expected new html page in Preview(without css style), but nothing happens on the current page. 如果单击了#submit按钮,则响应的状态代码为200,Chrome开发工具会在Preview(无CSS样式)中显示完整的预期新html页面,但当前页面上没有任何反应。

This is the Response: 这是响应:

<!DOCTYPE html>
<html>
    <head>
        // head stuff
    </head>
    <body>
       // Some stuff
    </body>
</html>

I used return HttpResponse(template.render(context, request)) 我用return HttpResponse(template.render(context, request))

My View-Function: 我的视图功能:

from django.http import HttpResponse

def another-view(request):
    if request.method == "POST":
        if request.POST.get("points"):
            points = int(request.POST.get("points"))
            template = loader.get_template('my_template.html')
            context = {'message': "any message"}
            return HttpResponse(template.render(context, request))

This is how my view function works, points are stored in Database and some magic happens, but all works fine and the Request Status Code is 200. 这就是我的视图函数的工作方式,将点存储在数据库中,并且发生了一些魔术,但是一切正常,请求状态代码为200。

I have unfortunately no idea what I've overlooked. 不幸的是,我不知道我忽略了什么。

The Response from AJAX ( the inner ajax() with url: "/another-view/") is the expected HTML Page, but nothin happens on the current Page. 来自AJAX的响应(URL为:“ / another-view /”的内部ajax())是预期的HTML页面,但在当前页面上没有发生任何反应。 I would like to replace the complete page 我想替换整个页面

I've found a solution to the problem. 我找到了解决问题的方法。 To redirect to a Django view function with POST data you can use the jQuery.redirect function which is usable after include the jquery.redirect.js from https://github.com/mgalante/jquery.redirect 要使用POST数据重定向到Django视图函数,可以使用jQuery.redirect函数,该函数在包含来自https://github.com/mgalante/jquery.redirect的jquery.redirect.js后可用。

USAGE: 用法:

/**
* jQuery Redirect
* @param {string} url - Url of the redirection
* @param {Object} values - (optional) An object with the data to send. If not present will look for values as QueryString in the target url.
* @param {string} method - (optional) The HTTP verb can be GET or POST (defaults to POST)
* @param {string} target - (optional) The target of the form. If you set "_blank" will open the url in a new window.
* @param {boolean} traditional - (optional) This provides the same function as jquery's ajax function. The brackets are omitted on the field name if its an array.  This allows arrays to work with MVC.net among others.
* @param {boolean} redirectTop - (optional) If its called from a iframe, force to navigate the top window. 
*/
$.redirect(url, [values, [method, [target, [traditional, [redirectTop]]]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM