简体   繁体   中英

jquery , ajax data sum cant get to work correctly

$.post('ajax_ceneizbaze.php', function(cenovnik){

                                    if(cenovnik){

                                        cenastr=cenovnik.cenastrana;
                                        cenadinamika=cenovnik.cenadinamika;
                                        cenabaza=cenovnik.cenabaza;
                                        cenakorpa = cenovnik.cenakorpa;
                                        cenacms = cenovnik.cenacms;
                                        inkrementodrzavanje = cenovnik.cenaodrzavanje;
                                        rezz = parseInt(cenastr+cenadinamika);
                                        alert(rezz);




                                   }
                                   else alert('bla bla..');


                                },'json');

initial value for cenastr is 25, and for cenadinamika is 50 ,Ajax works perfectly in this mine example, but when i try to sum values cenastr and cenadinamika i get output 2550 , instead 75? why i cant convert that to integer and to get sum of thoose two. it only output result in string format. i tried parseInt to place before sum operation but it doesnt helps.

you have to parseInt each of the strings:

rezz = parseInt(cenastr) + parseInt(cenadinamika);

Try that out

http://www.javascripter.net/faq/convert2.htm - this might help. You need to convert the strings to numbers before the calculation!

The + operator has a dual purpose. On strings it concatenates them:

"25" + "50" = "2550"

With numbers, it sums them.

25 + 50 = 75

Therefore we can deduce that your two variables are strings, and that you parse the result of concatenating them to an integer, giving you 2550.

You need to parse each individual value to an int before using the + operator to add them:

rezz = parseInt(cenastr,10) + parseInt(cenadinamika,10);

parseInt will be working on the result of the addition, which, both being strings, will be the concatenation.

Either:

parseInt(cenastr) + parseInt(cenadinamika)

or use the unary operator:

(+censtr) + (+cenadinamika);

Make sure the variable are numbers before adding:

cenastr= +cenovnik.cenastrana;
cenadinamika= +cenovnik.cenadinamika;
//...
rezz = cenastr + cenadinamika;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM