我正在尝试将json_encode中的数据附加到我的 PHP WHILE 循环中创建的 DIV 中。更清楚的是,这是我的演示小提琴。
我有一个带有唯一ID的DIV:办公桌(你看到的小盒子(。当我的"aht"按钮被单击时,它会show_aht.php运行。
我希望我的数据"时间"来自show_aht.php替换每个适当的"桌面"DIV中的数字,因此显示从我的脚本中检索的"时间"值。
问题:它没有显示,我遇到如何使用我的唯一ID附加/替换的问题
提前感谢!
map.php WHILE 循环,用于执行查询以创建桌面和工作站 DIV:
//desks
while($row = mysqli_fetch_assoc($desk_result)){
//naming values from coordinates table
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$sta_num = $row['station_number'];
$position = $row['ver_hor'];
//draw a DIV box at its X,Y coordinate
//if the desks belong in the section names below then assign the class name to make desks horizontal
$class = "desk_box_ver"; //by default make desks vertical, by assigning class name
if($position == "horizontal"){
$class = "desk_box_hor";//assign the class name to make desks horizontal
}
这是我希望数据"时间"使用 id = test_$id 替换 $sta_number 值的地方
//output all desks being read from the query
echo '<div class="' . $class . ' id="test_'.$id.'" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "'n";
}//end while
地图.php 阿贾克斯如何在 DIV 下方的 FOR 循环中追加 id = test_$id?
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<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 i'm GET ting?
dataType: 'json',
success : function(data){
alert(data);
//NOT WORKING PLEASE HELP
for(i = 0; i < data.length; i++){
$("#test_"+id).html(data[i])
}
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php - json_encode部分
/**comparing usernames from both arrays*/
$res = array();
foreach($memo_data as $m){
foreach($user_data as $u){
//if theres a matching username
//display user and time
if( ($m['memo_code'] == $u) && ($m['avg_handle_time'] != null) ){
$res[] = substr($m['avg_handle_time'],0,-3);//removing decimals
}
//else if matching user but no time, do not display time
elseif( ($m['memo_code'] == $u) && ($m['avg_handle_time'] == null) ){
$res[] = "NA";
}
}
}
$final_res = json_encode($res);
echo $final_res;
我会按照@jeroen的建议去做。 console.log(data);
成功之后。您也可以尝试complete: function(data) { ...
并记录数据,这样总会有结果。
另外,您使用POST
有什么特殊原因吗?在我看来,你正在GET
数据。
//NOT WORKING PLEASE HELP
for(i = 0; i < data.length; i++){
$("#test_"+id).html(data[i])
}
当然它不起作用,在您的 .success 函数中,您尝试从哪里获取变量 id ($("#test_"+id((?就我而言,你正在使用id作为javascript变量。所以。。它是在JavaScript范围内全局初始化的吗?如果是这样,变量是否有任何值?分析这一点,我得出结论,就在那里,由于id错误,JQuery没有追加。
如果使用 $.POST,确保你故意传递一些不相关的数据,只是为了测试。但可以肯定的是,使用 $。去。
发布一些反馈,看看修复后发生了什么,或者解释那里发生了什么。
我在这里找到了自己的解决方案:
success : function(data){
console.log(data);
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']); // set inner HTML
}
}
}//结束成功