jQuery .ajax call fails when '0' is entered
I've created a guess-the-number game using jQuery and PHP, and while it works fine when a number is entered (and also handles non-numbers well), when 0 is entered the Ajax call fails. As far as I can tell, when 0 is entered the variable $guess
sent to the server-side code isn't set properly, but I can't work out why - any ideas?
Form input:
<form id="guess" action="magicgubbins.php" method="get">
<p><input type="text" id="newguess" name="guess" value="" />
<input type="submit" value="Guess"></p>
</form>
jQuery:
<script type="text/javascript">
$(function() {
var magicno = Math.floor(Math.random()*11);
$('#guess').submit(function() {
var newguess = $('#newguess').attr('value');
if (!newguess) {
newguess = 'nonumber';
}
var form = $(this),
//formData = form.serialize(),
formData = {guess: newguess, magic: magicno},
formUrl = form.attr('action'),
formMethod = form.attr('method'),
responseMsg = $('#magicbox');
//show waiting message
responseMsg.hide()
.addClass('response-waiting')
.text('Please wait...')
.fadeIn(200);
$.ajax({
url: formUrl,
type: formMethod,
data: formData,
success: function(data){
// parse returned data
var responseData = jQuery.parseJSON(data),
klass = '';
switch(responseData.status){
case 'error':
klass = 'response-error';
break;
case 'success':
klass = 'response-success';
break;
}
// show new response message
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(klass)
.text(responseData.message)
.fadeIn(200,function(){
if (responseMsg.hasClass('response-success')) {
$('#description').hide();
$('#magicbox').hide();
$('#status').text('You win!').show();
}
// timeout response message
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(klass);
});
},3000);
});
});
}
});
return false;
});
});
</script>
Server-side code:
<?php
$magic = htmlentities($_GET['magic']);
$guess = htmlentities($_GET['guess']);
if(empty($magic)){
$status = "error";
$message = "No magic number set!";
} else if (empty($guess)) {
$status = "error";
$message = "Take a guess!";
} else {
if(is_numeric($guess)) {
if($guess == $mag开发者_开发百科ic) {
$status = "success";
$message = "Correct! " . $magic . " is the magic number.";
} else {
if ($guess > $magic) {
$status = "error";
$message = "Wrong! " . $guess . " is too high.";
} else {
$status = "error";
$message = "Wrong! " . $guess . " is too low.";
}
}
} else {
$status = "error";
$message = "That's not a number!";
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
exit;
}
?>
Have you debugged the call using Firebug Net console window (or the equivalent in Google Chrome)?
Also don't forget PHP treats numeric 0 the same as false and an empty string in boolean operators. Calling empty(0); will return true. Calling empty("0"); will not.
精彩评论