【发布时间】:2011-03-20 00:26:58
【问题描述】:
<form id="login_frm" method="post" action = "/login/user_auth/">
<fieldset>
<legend>Login:</legend>
<label for="id_email">Email</label>
<input type="text" name="email" id="id_email" />
<label for="id_password">Password</label>
<input type="password" name="password" id="id_password" />
</fieldset>
<input name = "login" type="submit" value="Login" />
</form>
$(document).ready(function () {
$('#login_frm').submit(function() {
var $form = $(this);
$.post('/login/user_auth/' , form.serialize(), function(data) {
// alert ("function");
alert (data);
});
return false;
});
});
Django 视图:
def login_user(request):
if request.method == 'POST':
# perform all logic / and db access
data = "hello"
return HttpResponse(data)
# return HttpResponse ('success.html')
我整个下午都被困在这个问题上。
当我返回
data作为响应时,由于某种原因,浏览器通过加载一个仅写有“Hello”的空白网页来显示“Hello”;在上面的 JavaScript 函数中,从未调用过alert (data);(我不明白为什么)。我无法呈现 success.html。我相信如果我在HttpResponse里面写render_to_response,我会解决这个问题的。不过,我认为让第 1 点发挥作用是首要任务。
目标
发布后,我想捕获服务器返回的响应(无论是“hello”消息,还是显示成功消息的网页 - 存储在“success.html”中)并将其显示在login_frm 的位置,无需浏览器刷新新网页。
【问题讨论】:
-
在普通页面中不是“hello”,而是在调用 [data = “hello” return HttpResponse(data)] 时期望返回什么?也许您应该更改现有对象而不是发送新的 HttpResponse 对象? (我的 Django 技能真的很尘土飞扬,如果这是一个无用的评论,请见谅)
-
我不太明白你的问题:你明确地返回了一个只有“hello”的响应,那么你为什么希望加载 HTML 和 JavaScript?
-
@AntiDog,我只是不希望网页被刷新,而是作为一个post方法,应该返回结果并且应该在javascript函数中执行行警报(数据)。 Yuji的解决方案修复了它,是变量名错误。