json/jquery to second div returns NaN
I'm fetching a row of data from a mysql-server using php, then encode it to a json array. I then pull the information using the following PHP. The strange part is that if I send "vname" to it's own div, I get "NaN" as a result. If I display it in the first div, everything turns out fine. Any idea why? Btw, is it right of me to use .ht开发者_如何学Cml to send to the div? I've tried .appendTo and .text with the same result.
<h3>Output: </h3>
<div id="output">Content1</div>
<div id="username">content2</div>
<script id="source" language="javascript" type="text/javascript">
$(function() {
$.ajax({
url: 'api.php',
dataType: 'json',
success: function(data) {
var id = data[0];
var vname = data[1];
var message = data[2];
var timestamp = data[3];
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
}
});
});
</script>
I;m going to guess its because of the first +
. Javascript is trying to add nothing to all of the other stuff, which would output a NaN
$('#output').html(id +timestamp +message );
$('#username').html( vname );
In this case text()
might be a better to use because there aren't any html elements in your strings, but it really doesn't matter.
+variable
is shorthand for casting a variable to a number: Unary plus/minus (MDN)
var x = "5";
+x; //Gives you 5 as a number
x = "Hello";
+x; //Gives you NaN
You can use regular append.
$('#output').append(id + timestamp + message);
$('#username').append(vname);
$('#output').html(+id + timestamp + message);
$('#username').html(+vname);
These are probably your problem. The plus sign in front of the variables would throw an error. If you are trying to concatenate (add together) the existing the value and your response from the ajax change it to some thing like this:
$('#output').html($('#output').html() + id + timestamp + message);
$('#username').html($('#username').html + vname);
精彩评论