Problem in login page using form based authentication
I want a login page in which 开发者_Python百科 if any user types invalid password or username after clicking submit button, then the user will be displayed an error message on the same page.
What should I have to make this requirement enable? Is this possible with ajax or javascript?
Yes, this is possible with Ajax. It's easiest, frankly, if you use a library like Prototype, jQuery, Closure, etc., because they smooth out browser differences and such for you, and have a lot of built-in functionality.
For example, here's a fairly succinct way you can submit a form and look at the response using Ajax with Prototype:
$('formid').request({
onSuccess: function(response) {
// Request succeeded, check result for whether login was valid
}
});
(That assumes the form has the id "formid".)
Here's a more complete example, which also shows how you hook into the submission process. You might trigger that code by hooking the submit
event on the form and sending the Ajax request instead:
$('formid').observe('submit', function(event) {
// Prevent the standard form submission
event.stop();
// Do it via Ajax instead, including an additional flag telling
// the server that this is an Ajax call
this.request({
parameters: {viaAjax: true},
onSuccess: function(response) {
// Request succeeded, check result for whether login was valid
if (response.responseJSON &&
response.responseJSON.loginOkay) {
// Login worked!
}
}
});
});
The above does these things:
- Hooks up a Javascript handler for when the user submits the form
- Handles that event by cancelling the usual form submission and sending an Ajax call instead
- Along with the form data, we also include a
viaAjax
flag telling the server that we're sending the form via Ajax
The server should expect the form to arrive either with or without the viaAjax
flag. If the flag is there, it means the browser supports Javascript and the form was submitted that way, and so it should just return a flag telling us whether the login was okay (in the above I've assumed it will return JSON-formatted data {"loginOkay": true}
, which means it should set the content type to application/json
). If the flag isn't there, Javascript is disabled on the browser and the server should handle the form submission in the normal way, returning a full HTML page. (This business of handling it regardless of whether Javascript is enabled is called "progressive enhancement" or "graceful degradation".)
精彩评论