簡體   English   中英

在對django視圖進行post ajax調用后重定向到另一個頁面

[英]Redirecting to a different page after post ajax call made to django view

我一直在嘗試使這段簡單的代碼正常工作,但仍然無法實現。 通過了多個其他鏈接。 無法弄清楚我做錯了什么。 我有一個JavaScript函數submitData()submitData()需要對Django視圖進行ajax post調用。 django視圖基本上只需要檢查請求是否為post ,如果是post ,則必須重定向到另一個頁面。

我的javascript函數submitData()如下所示,並且還添加了代碼部分,該部分代碼負責將csrf令牌與post請求一起發送。

function submitData()
    {
      $.post('/loggedin/',{"fname":"name1","lname":"name2"},function(data){
        alert("Back from views.py");

      });
    }

$(function () {
        $.ajaxSetup({
            headers: { "X-CSRFToken": getCookie("csrftoken") }
        });
    });

function getCookie(c_name)
    {
        if (document.cookie.length > 0)
        {
            c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1)
            {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
     }

在我的views.py ,我有以下代碼,

def loggedin(request):
    if request.method == "POST":
        fname = request.POST.get('fname')
        print fname #The code comes here, prints the fname
        args = {}
        args.update(csrf(request))
        return render_to_response('loggedout.html',args,context_instance=RequestContext(request)) #This does not redirect to a different page
    print "outside in loggedin"
    args = {}
    args.update(csrf(request))
    return render_to_response('loggedin.html',args, RequestContext(request))

進行post調用時,將打印fname,但是不會發生由函數render_to_response()的重定向。 而是返回post調用,並警告post調用“從views.py返回”中的警報語句。 我不確定我錯過了什么。

您可以在post成功完成后使用javascript進行重定向。

function submitData()
    {
      $.post('/loggedin/',{"fname":"name1","lname":"name2"},function(data){
        alert("Back from views.py");
        window.location = 'yourpage.hmtl'
      });
    }

或者,如果您正在發送頁面名稱作為響應,則可以使用data重定向到頁面。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM