dongpu9481 2015-11-27 10:01
浏览 102
已采纳

坚持使用jQuery动态显示变量

When a user chooses a date from the drop-down list, the number of nights changes according to that new date.

Following this tutorial www.w3schools.com/php/php_ajax_database.asp I wrote the following code, but when I change the date on the list, I just get a message saying undefined in the <div id="stats">

<?php
    $dates = "";
    foreach ($check_ins as $check_in):
        $dates .= '<option value= "' . $check_in['check_in'] . '">' . $check_in['check_in'] . '</option>';
    endforeach;

    $nights = $check_ins[0]['nights'];
    if (!empty($_POST['newDate'])){
        $nights = 0;
        foreach ($check_ins as $check_in):
            if ($check_in['check_in'] === $_POST['newDate']){
                $nights += $check_in['nights'];
            }
        endforeach;
    }

?>

<html>
    <head>
        <title>Bookings stats</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script>
            /*function dynamicDates() {
                var d = $("#dates").val();
                $.post("metrily.php", { newDate: d });
            }*/
            function dynamicDates(newDate){
                if (newDate == ""){
                    document.getElementById("stats").innerHTML = "";
                    return;
                } else {
                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            document.getElementById("stats").innerHTML = xmlhttp.responseTest;
                        }
                    };
                    xmlhttp.open("POST", "hotel.php", true);
                    xmlhttp.send("newDate=" + newDate);
                }
            }
        </script>
    </head>
    <body>
        <b>Check-in: </b>
        <select id="dates" name="check_in" onchange="dynamicDates(this.value)"><?php echo $dates; ?></select>
        <br></br>
        <div id="stats">
            <b>Nights: </b><?php echo $nights; ?>
        </div>

    </body>
</html>
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-11-27 11:07
    关注

    If you have jQuery, use it:

    function dynamicDates(newDate){ 
      if (newDate == ""){ 
        $("#stats").empty(); return; 
      } else { 
        $.post("hotel.php",{"newDate":newDate},function(data) { $("#stats").html(data); }); 
      } 
     } 
    

    assuming hotel.php only does some calculation and then

    <?php echo $nights; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:功能监听网页
  • ¥50 comsol稳态求解器 找不到解,奇异矩阵有1个空方程返回的解不收敛。没有返回所有参数步长;pid控制
  • ¥15 怎么让wx群机器人发送音乐
  • ¥15 fesafe材料库问题
  • ¥35 beats蓝牙耳机怎么查看日志
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群