ParseInt 不适用于 Jquery ajax 响应
我在从 ajax 响应获取整数时遇到了一个特殊的问题。每当我调用以下代码时,尽管 data 是字符串,但 parseInt(data) 返回 NaN 。
function poll() {
$.ajax({
type: "GET",
dataType: "html",
url: 'images/normal/' + userId + '/' + saveCode + 'progress.txt',
error: function() {poll();},
success: function(data) {
// Change the text
$('#loading_text').html(data + '% complete');
// Change the loading bar
max = 357;
current_percent = parseInt(data); // returns NaN
$('loading_bar').width(Math.round(max * (current_percent / 100)));
// Call the poll again in 2 seconds
if (loaded != true)
{
setTimeout( poll, 2000);
}
}
});
}
在 firebug 中, typeof(data) 是 string 并且 data = "89" (或 1-100 之间的另一个数字),但它仍然不起作用。有什么线索吗?
I am having a peculiar problem with getting an integer from an ajax response. Whenever I call the following code, parseInt(data) returns NaN despite data being a string.
function poll() {
$.ajax({
type: "GET",
dataType: "html",
url: 'images/normal/' + userId + '/' + saveCode + 'progress.txt',
error: function() {poll();},
success: function(data) {
// Change the text
$('#loading_text').html(data + '% complete');
// Change the loading bar
max = 357;
current_percent = parseInt(data); // returns NaN
$('loading_bar').width(Math.round(max * (current_percent / 100)));
// Call the poll again in 2 seconds
if (loaded != true)
{
setTimeout( poll, 2000);
}
}
});
}
In firebug, typeof(data) is string and data = "89" (or another number from 1-100) yet it still isn't working. Any clues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,您也可以尝试使用加号,而不是使用 parseInt
据我所知,+ 号和 parseInt 的不同之处在于,当您解析空白或空白字符串时,parseInt 返回 NaN,而 + 返回 0
So you can also give it a try with Plus + sign, instead of using parseInt
A different with + sign and parseInt as far as I know is when you parse blank or whitespace strings, parseInt return NaN, and + returns 0
您确定数据正是“89”吗?如果字符串中的第一个非空白字符无法转换为数字,则
parseInt()
返回 NaN。另外,使用 parseInt 指定基数是一个很好的做法,以强制进行您正在寻找的转换。尝试
parseInt(data, 10)
。Are you sure the data is exactly "89"? If the first non-whitespace character in the string can't be converted to a number,
parseInt()
returns NaN.Also, it's a good practice to specify the radix with parseInt, to force the conversion that you're looking for. Try
parseInt(data, 10)
.尝试以编程方式浏览字符串的每个字符,也许有一个不可打印的字符阻止了 parseInt 的执行。
Try browsing every character of the string programmatically, perhaps there's an unprintable character that's preventing the parseInt to execute.