【发布时间】:2014-11-24 14:50:21
【问题描述】:
我会尽量简单地描述我的问题。我有这个 AJAX 调用来获取一个 Json_encoded 数组。随着“aht_value”被检索,我得到了一个彩色背景 从绿色到红色(我在做热图)。我的值正在正确输出。
问题: 我的“colorMe”功能。我不确定我做错了什么,或者我是否将所有功能都放在了错误的位置,因为我在我的“成功”内以及在我的 FOR 循环之后做所有事情,如下所示。但是,如果我将“min”替换为 100,将“max”替换为 1800,则会显示颜色。
提前致谢。
来自 show.php 的数组:
[{
"username":"OXGOR",
"aht_value":"241",
"station":"B20"
},
{
"username":"AISAI2",
"aht_value":"199",
"station":"B21"
},
{
"username":"CAPAP3",
"aht_value":"NA",
"station":"B10"
}]
map.php - JS 部分
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"GET",
url : "show_aht.php",
data:{ } , // do I need to pass data if im GET ting?
dataType: 'json',
success : function(data){
var min = data.reduce(function(prev, curr) {
return isNaN(curr['aht_value']) || prev < curr['aht_value'] ? prev : curr['aht_value'];
}, 1000000);
alert(min); //not returning the correct number
var max = data.reduce(function(prev, curr) {
return isNaN(curr['aht_value']) || prev > curr['aht_value'] ? prev : curr['aht_value'];
}, -1000000);
alert(max); //nor returning the correct number
//function for calculation of background color depending on aht_value
function conv(x){
return Math.floor((x - min) / (max - min) * 255);
}
//function for background color
function colorMe(v){
return "rgb(" + conv(v) + "," + (255-conv(v)) + ",0)";
}
//going through all DIVs only once with this loop
for(var i = 0; i < data.length; i++) { // loop over results
var divForResult = $('#desk_' + data[i]['station']); // look for div for this object
if(divForResult.length) { // if a div was found
divForResult.html(data[i]['aht_value']).css("background-color", colorMe(data[i]['aht_value']));
}//end if
}//end for
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show.php:我使用json_encode的地方
$result = array();
foreach ($memo as $username => $memodata) {
if (in_array($username, array_keys($user))) {
// Match username against the keys of $user (the usernames)
$userdata = $user[$username];
//if AHT is null give N/A as value
if (is_null($memodata['aht_value'])) {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => 'NA',
'station' => $userdata['station']
);
}//end inner if
//else give the actual value of AHT without the decimals
else {
$result[] = array( 'username' => $userdata['username'],
'aht_value' => substr($memodata['aht_value'],0,-3),
'station' => $userdata['station']
);
echo json_encode($result);
如果我在 colorMe 函数中手动将最小值设置为 100,将最大值设置为 1800,则此方法有效: what is suposd to look like
每当我使用最小值和最大值计算时,如下所示,这会返回我的错误颜色 not giving right colors
【问题讨论】:
标签: javascript php jquery arrays ajax