Returning a proper response for post request in Django
<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 View:
def login_user(request):
if request.method == 'POST':
# perform all logic / and db access
data = "hello"
return HttpResponse(data)
# return HttpResponse ('success.html')
I have been stuck on this all afternoon.
When I return
data
as my response, for some reason, the browser displays "Hello" by loading a blank webpage with just "Hello" written on it; in the JavaScript function above,alert (data);
开发者_如何学运维is never called (I cannot understand why).I am unable to render the success.html. I believe that if I write render_to_response inside the HttpResponse, I will solve this problem. However I think making point 1 work is a first priority.
Goal
After the post, I would like to capture the returned response from the server (whether it is just the "hello" message, or a webpage that displays a success message- stored in "success.html") and display it in place of the login_frm
without having the browser refresh a new webpage.
Interesting. form
is undefined (you defined it as $form) and changing to $form
fixed the problem.
$(document).ready(function () {
$('#login_frm').submit(function() {
var $form = $(this);
$.post('/login/user_auth/' , $form.serialize(), function(data) {
// alert ("function");
alert (data);
});
return false;
});
});
You might want to use something like event.preventDefault()
so that future errors are not hidden from you like this. $('form').submit(function(e){ e.preventDefault(); .....})
精彩评论