Question

Same variable (119), same constant (100). Both are correctly interpreted as numbers when using the subtraction and multiplication operators, however not so when using the addition operator - the result is a string (119100). However when I apply the parseFloat function with the addition operator I get the correct result (219). Does Jquery interpret the '+' operator as a string concatenator?

var newvotes = 0;

$(document).ready(function(e) {

//alert(1);


$('.vote').children().click(function(e) {
e.preventDefault(e);
var vote = $(this).text();
var timestamp = 1369705456;

$.ajax({
type: 'POST',
url: 'forumvote.php',
data: {'timestamp' : timestamp, 'vote': vote},
success: function(data, textStatus) {
  newvotes = data;

 },

//dataType: 'text',
async:false,
});

alert(newvotes); //119
var newvar = newvotes*100; 
var newvar2 = newvotes-100; 
var newvar3 = newvotes+100;
var newvar4 = parseFloat(newvotes) + parseFloat(100); 
alert(newvar); //11900 ok
alert(newvar2); //19 ok
alert(newvar3); //119100 returns as a string
alert(newvar4); //219 ok

})

Était-ce utile?

La solution

Its not jQueries fault. Its just what Javascript does.

If you look at the type of newVotes you'll find its a string. ( typeof(newVotes) ). The binary operators * and - convert their arguments to numbers. The binary operator + if either argument is a string converts the other arguments to strings. Otherwise it converts them to numbers.

So all you need to do is convert your data to a number in your success callback and all will work for you:

$.ajax({
type: 'POST',
url: 'forumvote.php',
data: {'timestamp' : timestamp, 'vote': vote},
success: function(data, textStatus) {
  newvotes = parseFloat(data);

 },

//dataType: 'text',
async:false,
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top