2016-01-05 39 views
1

在這裏,我通過ajax和json獲取記錄。 如果變量有,我會得到值。 但是,如果變量「性能」具有空值,則顯示NaN。 而不是NaN,我想打印數字值,如00.00如果變量具有空值,那麼獲得NaN

這可能嗎?如果是,那麼如何? 謝謝。

我的代碼,

function emp_month_perf(){ 

      jQuery.ajax({ 
       url: "<?php echo base_url(); ?>grade_tasks/emp_monthly_performance", 
       data:'', 
       type:"GET", 
       dataType: "json", 
       success:function(data){ 

        var total_month_earn = data.total_earn_point; 
        var total_month_point = data.total_point; 
        var performance; 
        var per_color; 
        //var radius = "20px"; 
        //alert(total_point); 
        performance = (((total_month_earn)/(total_month_point))*100).toFixed(2); 
        if(performance>80) 
        { 
         per_color = "#33CF53"; 
        } 
        else if(performance>=60 && performance<=80) 
        { 
         per_color = "#E0C533"; 
        } 
        else 
        { 
         per_color = "#E12827"; 
        } 
        //document.getElementById("monthperformance").style.borderRadius = radius; 
        document.getElementById("monthperformance").style.backgroundColor = per_color; 
        $('#monthperformance').html(performance); 
       }, 
       error:function(){} 
       }); 
       } 
       setInterval(emp_month_perf, 300000); 
+2

什麼變量爲空? – epascarello

回答

4

使用或操作人員的數量設置爲零。

var total_month_earn = data.total_earn_point || 0; 
var total_month_point = data.total_point || 0; 

但現在你可以有1/0這將是無窮大。 :)

其他選項是檢查NaN並將該值設置爲零。

var performance = (((total_month_earn)/(total_month_point))*100); 
var formatted = isNaN(performance) ? "00.00" : performance.toString(2); 
+0

謝謝@epascarello:但這不適合我。如果變量具有空值,則應通過defaulf 00.00進行打印。 –

+0

我不知道'performance'具有'null'的值。它應該是「NaN」或「#。##」或「Infinity」 – epascarello

+0

在第二個選項中,我必須在html響應中設置變量「formatted」。對? –

0

修復是如下更換

performance = (((total_month_earn)/(total_month_point))*100).toFixed(2); 

隨着

try { 
    performance = (((total_month_earn)/(total_month_point))*100).toFixed(2); 
    performance=isNaN(performance) ? "00.00" : performance; 
} 
catch(err) { 
    performance="00.00"; 
} 
+0

UM,沒有錯誤發生...... – epascarello