我一直在试图让这个简单的代码工作正常,但仍然无法。已经通过多个其他链接。我无法弄清楚我做错了什么。我有一个JavaScript函数submitData()
,它只需要调用一个django视图就可以调用ajax post
。 django视图基本上只需检查请求是否为post
,如果是,则必须重定向到另一个页面。重定向到不同的页面后发送ajax调用django视图
我的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
调用“Back from views.py”中的警报语句。我不确定我错过了什么。
请显示'render_to_response'的代码 – Mairaj
'views.py'中的'loggedin()'函数具有'render_to_response'()。我只是使用由django的django.shortcuts库提供的'render_to_response()'函数。代码如? – nidHi
这里根本没有重定向。 –