我正在使用php文件从mysql中检索一些值。
结果如下所示:4.7647058823529
。
我正在使用我的代码加载这个结果,然后它很好用。
4.7
而不是4.7647058823529
为什么警告不要出现这个val?
$(".getfinalrate").load("update.php?tpid=" + id);
var res = $(".getfinalrate").text();
$(".getfinalrate").fadeIn();
alert (res);
我的PHP代码:
<?php
if(isset($_GET['tpid']))
{
require "connection.php";
$videid = $_GET['tpid'];
$id = mysql_escape_string($videid);
$thecounter = mysql_query("SELECT COUNT(*) AS sumury FROM user WHERE id = '$id'");
$numm = mysql_fetch_array($thecounter);
$getallrecords = $numm["vote_action"];
$queryf="SELECT SUM(vote_action) AS `total` from user WHERE id = '$id'";
$resultf=mysql_query($queryf);
while($rowf=mysql_fetch_assoc($resultf))
$totals = $rowf['total'];
if ($getallrecords > $totals){
$finalratepoints = $getallrecords / $totals;
echo $finalratepoints;
}else{
$finalratepoints = $totals / $getallrecords;
echo $finalratepoints;
}
}
?>
谢谢!
答案 0 :(得分:3)
因为load
异步,所以:
$(".getfinalrate").load("update.php?tpid=" + id); // *Starts* the load
var res = $(".getfinalrate").text(); // Gets the text *BEFORE* the load completes
所以res
最终会在<{em> .getfinalrate
之前获得中的第一个load
元素。
解决方案是使用load
的回调函数:
$(".getfinalrate").load("update.php?tpid=" + id, function() {
// This function is called when the load is complete
var res = $(".getfinalrate").text();
$(".getfinalrate").fadeIn();
alert (res);
});
如何将tis值转换为如下所示:
4.7
而不是4.7647058823529
最好在Stack Overflow上针对每个问题提出一个问题。
假设您想要res
作为数字,答案是:
res = Math.floor(4.76747 * 10) / 10;
如果您想将它作为字符串,您可能希望这样做:
res = (Math.floor(4.76747 * 10) / 10).toFixed(1)
...确保没有微小的小分数位,因为浮点不是很精确。
答案 1 :(得分:1)
此代码没有按您认为的那样执行:
$(".getfinalrate").load("update.php?tpid=" + id);
var res = $(".getfinalrate").text();
$(".getfinalrate").fadeIn();
alert(res);
你看,.load()
是异步的。因此,在完成之前,此代码的其余部分将继续执行。如果此代码开始执行时res
为空,则$(".getfinalrate").text()
将为空。
你需要异步地思考这个问题。当.load()
执行时,它将继续在自己的线程中。响应该线程需要发生的任何事情都需要在该线程执行的回调中发生。 .load()
为这样的回调函数提供了一个参数:
$(".getfinalrate").load("update.php?tpid=" + id, function () {
var res = $(".getfinalrate").text();
$(".getfinalrate").fadeIn();
alert(res);
});
在此结构中,.load()
在完成其AJAX请求时将调用匿名内联函数。在调用.load()
之后的任何代码都将立即继续,但函数中的代码将延迟到异步调用完成。
答案 2 :(得分:1)
如何从其他页面获取值需要Ajax。
$.get("update.php?tpid="+id, function(response){
//Alert Response
alert(response);
$(".getfinalrate").html(response);
}):
答案 3 :(得分:0)
var res = $(".getfinalrate").text();
res = Math.floor(res * 10)/10;
alert(res);