2013-11-03 18 views
0

我正在使用PHP文件從MySQL中檢索一些值。 結果如下所示:4.7647058823529雖然html值加載警報不顯示它

我將此結果與我的代碼波紋管加載到一個div,它工作的很好。

  1. 如果我使用警報來獲取此值alert不顯示值。
  2. 我怎樣才能TIS值轉換成看起來像這樣: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

我們應該看到PHP代碼告訴如何... –

回答

1

這個代碼不執行你認爲事情是這樣的:你看

$(".getfinalrate").load("update.php?tpid=" + id); 
var res = $(".getfinalrate").text(); 
$(".getfinalrate").fadeIn(); 
alert(res); 

,​​是異步的。所以在它完成之前,這段代碼的其餘部分將繼續執行。因此,如果$(".getfinalrate").text()在此代碼開始執行時爲空,那麼res將爲空。

您需要異步考慮此問題。當​​執行時,它將繼續在它自己的線程中。任何需要響應該線程發生的事情都需要在該線程執行的回調中發生。​​提供參數用於這種回調函數:

$(".getfinalrate").load("update.php?tpid=" + id, function() { 
    var res = $(".getfinalrate").text(); 
    $(".getfinalrate").fadeIn(); 
    alert(res); 
}); 

在這種結構中,匿名內聯函數將由​​當它完成它的AJAX請求調用。此調用​​之後的任何代碼都將立即繼續,但函數中的代碼將推遲到異步調用完成。

3

load由於是異步,所以:

$(".getfinalrate").load("update.php?tpid=" + id); // *Starts* the load 
var res = $(".getfinalrate").text();    // Gets the text *BEFORE* the load completes 

所以res結束有任何第一.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

這是最好問一個堆棧溢出每個問題的問題。

假設你想res多項答案是:

res = Math.floor(4.76747 * 10)/10; 

如果你想把它當作一個字符串,你可能會想這樣做:

res = (Math.floor(4.76747 * 10)/10).toFixed(1) 

...以確保並不是很小的小數位,因爲浮點不是很精確。

+0

所以請怎樣才能使它發揮作用? –

+0

@IreneT .:對不起,我被第二個問題分散了。查看更新。 –

1

如何從其他頁面獲取值需要使用Ajax。

$.get("update.php?tpid="+id, function(response){ 
    //Alert Response 
    alert(response); 
    $(".getfinalrate").html(response); 

}): 
0
  1. 你需要做的SYNCHRON AJAX請求。看看這個:http://api.jquery.com/jQuery.ajax/特別是在異步選項。但要小心,整個網站將被阻止,直到加載完成。
  2. var res = $(".getfinalrate").text();
    res = Math.floor(res * 10)/10; alert(res);