json/jquery 到第二个 div 返回 NaN
我使用 php 从 mysql 服务器获取一行数据,然后将其编码为 json 数组。然后我使用以下 PHP 提取信息。奇怪的是,如果我将“vname”发送到它自己的 div,结果会得到“NaN”。如果我将它显示在第一个 div 中,一切都会很好。知道为什么吗?顺便说一句,我使用 .html 发送到 div 是否正确?我尝试过 .appendTo 和 .text 得到相同的结果。
<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 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 .html 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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我猜测是因为第一个
+
。 Javascript 试图向所有其他内容添加任何内容,这将输出NaN
在这种情况下,
text()
可能更好用,因为没有任何html 元素在你的字符串中,但这并不重要。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 aNaN
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
是将变量转换为数字的简写:一元加/减 (MDN)您可以使用常规 追加。
+variable
is shorthand for casting a variable to a number: Unary plus/minus (MDN)You can use regular append.
这些可能都是你的问题。变量前面的加号会引发错误。如果您尝试连接(添加在一起)现有值和 ajax 的响应,请将其更改为如下所示:
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: