随着数量的增加,我正在使用 ajax 来生成书籍的价格。我遇到的唯一问题是当我尝试生成总计时(参见 JS 代码),它导致了一些问题(值将连接而不是相加)。我通过四舍五入变量“数量”解决了这个问题。但我试图理解为什么会发生连接。这是我的 PHP 代码:
if(isset($_GET["amount1"]) )
{
$amount1 = $_GET["amount1"];
$error="";
if($amount1 == "" || !preg_match("/^[0-9]+$/", $amount1))
{
$error .= "Please enter a valid number";
echo $error;
}
else{
echo round($amount1*16.65, 2);
}
}
这是JS代码:
if(xhr.status == 200 && xhr.readyState == 4)
{
var res = xhr.responseText;
if(res.match(/\d+/)== null){
document.getElementById("err3").innerHTML = res;
document.getElementById("book3").innerHTML = "";
total(0,3);
}
else{
document.getElementById("book3").innerHTML = res;
document.getElementById("err3").innerHTML = "";
total(res,3);
}
}
var book1 = 0;
var book2 = 0;
var book3 = 0;
function total(amount, book)
{
// amount = Math.round(amount*100)/100; --> this is what solved it but I don't
//know why I need it since amount was rounded by PHP code
if( book == 1)
book1 = amount;
if( book == 2)
book2 = amount;
if( book == 3)
book3 = amount;
var total = book1 + book2 + book3;
document.getElementById("total").innerHTML = total;
}
谢谢