jQuery .ajax request doesn't have any effect
I'm trying to make a jquery login system, but when I submit the form, the animated gif appears but nothing else.
Here is the code:
$(function(){
// Quand le formulaire est envoyé
$('#submit').click(function () {
// Fade out
var html = '<div id="head">Connexion en cours...</div>'+
'<div style="width:100%; text-align: center; margin-top:80px;"><span id="status">Prise de contact avec le serveur</span><span id="img"><br><img src="../img/loaders/bar_blue.gif"></span></div>';
replaceandfade('#center',html, 10);
$('#user').attr("disabled", true);
$('#pswd').attr("disabled", true);
var user = $('#user').val();
var pswd = $('#pswd').val();
// On envoie les infos de connexion
$.ajax({
type: "POST",
开发者_开发问答 url: "ajax_login.php",
data: "user=bob&pswd=bob",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$("#status").html("En attente de la réponse");
alert(data);
if(data.login == "failed"){
$("#img").html('');
$("#status").html("Le nom d'utilisateur ou le mot de passe saisie est invalide");
} else if(data.login == "success"){
$("#status").html("Connexion aprouvé, un instant...");
} else {
$("#status").html("Une erreur est survenu.");
};
}
});
});// END OF #submit.click
}) // END OF onload
The ajax_login.php page returns: {"login":"failed"}
But for now it doesn't do anything.
replaceandfade
function
function replaceandfade(div, content, sec) {
setTimeout(function() {
$(div).fadeOut("fast", function() {
$(div).html(content);
$(div).fadeIn("fast", function() {});
});
}, sec)
}
Your request doesn't handle the error outcome, and so if the request fails (for example the server could not be found, or more likely the response is a 500 server error), then nothing will happen.
You can add a error handler using the error
function, for example:
$.ajax({
// Other parameters
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Request failed");
}
});
Alternatively (or additionally) you can use the complete
function to specify actions that should happen when the request ends, be it with a success or fail outcome.
See the documentation for more information.
精彩评论