添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

Hi there,

I work on a project in Django and want to use ajax for one task:

I want to pass data, after it was processed by ajax, from my template file to my views.py file (with a POST request), to again make it visible in my templates file.

Templates-file → Proccessed data → POST-request → views.py → Template-file

But it just wont work for me.

Did I make a mistake?

My HTML-Templates-File :

<script type="text/javascript">
    var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
    function csrfSafeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    $.ajaxSetup({
        beforeSend: function (xhr, settings) {
            if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
    $.ajax({
        url: "/save",
        data: {
            'value': inputDataArray  //I have already defined "inputDataArray" before
        success: function (res, status) {
            alert(res);
            alert(status);
        error: function (res) {
            alert(res.status);                                                                                                                          
</script>

My views.py file:

def save(request):
    if request.method == 'POST':
        request_getdata = request.POST.get("value", None) 
    return render(request, "response.html", {"data":request_getdata})     

And my urls-py file:

urlpatterns = [
    path('', views.index , name='index'),
    path('save', views.save , name='save'),]

So I try display it at " response.html " with…

{{data}}

…but it just will reload the current page and does not pass any data to the response.html-file.

Does anyone knows what my error is here?

Thanks so much in advance