jQuery .attr()没有按预期响应

时间:2013-10-30 23:48:58

标签: jquery ajax

我有一个文本字段,它可以保存天数之间的差异。我需要用它来计算我页面上的内容。但是,出于某种原因,当我执行undefined时,它会以console.log()的形式返回。有什么想法吗?

<script>
        $(document).on('change', '#unitselector', function()
        {
            var unit = $('select option:selected').text();
            var rate = $(this).val();
            var tax = $('select option:selected').attr('label');
            var depart=$('#departdate').val();
            var arrival = $('#arrivaldate').val();
            var dataString = {unit:unit, depart:depart, arrival:arrival};
            console.log(dataString);
            //console.log($('.extracharges').serialize());
            $.ajax({
                type: "POST",
                url: "classes/unit_info.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $('.unitinfolist').html(html);
                }
            });

            var days = $('#days').attr('name');
            var days2 = $('#days').attr('value');
            console.log('days: '+days);
            console.log('days: '+ days2 );
            $('.rentalcharges').find('#rent').val(rate*days);
        });
    </script>

和PHP

$arrive = $_POST['arrival'];
$leave = $_POST['depart'];

$a = date_create($arrive);
$d = date_create($leave);
$diff = date_diff($d,$a);

echo '<input type="text" id="days" value="'.$diff->d.'" name="'.$diff->d.'" />';

1 个答案:

答案 0 :(得分:1)

ajax调用是异步的,因此即使您在ajax调用之后编写了日志代码,也要在从服务器返回之前记录这些值。

将代码移动到ajax成功处理程序中,如下所示:

<script>
        $(document).on('change', '#unitselector', function()
        {
            var unit = $('select option:selected').text();
            var rate = $(this).val();
            var tax = $('select option:selected').attr('label');
            var depart=$('#departdate').val();
            var arrival = $('#arrivaldate').val();
            var dataString = {unit:unit, depart:depart, arrival:arrival};
            console.log(dataString);
            //console.log($('.extracharges').serialize());
            $.ajax({
                type: "POST",
                url: "classes/unit_info.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $('.unitinfolist').html(html);
                    var days = $('#days').attr('name');
                    var days2 = $('#days').attr('value');
                    console.log('days: '+days);
                    console.log('days: '+ days2 );
                    $('.rentalcharges').find('#rent').val(rate*days);
                }
            });

        });
    </script>