美元.在代码再次执行之前,Get不会起作用


$.get doesn’t work until the code is executed another time

在我的主页中,我从数据库中填充了一个select元素,如下所示:

<select id="report" class="selectpicker input-sm">
    <option value=''>Choose a date</option>
    <?php foreach($this->report as $report) {?>
        <option><?php echo $report->timepoint_name;?></option>
    <?php } ?>
</select>

我希望当我选择一个选项时,该选项的文本将被添加到我的会话变量中,我认为使用Ajax来实现这一点。在同一文件中,我添加了以下javascript代码:

$('#report').on('change', function() {
    var report = $('#report').find(':selected').text();
    $.get("ajax.php", {'rep':report}, function(data,status){
        alert("Data: " + data + "'nStatus: " + status);
    });
});

当我从我的应用程序注销时,我使用php函数destroy_session()销毁会话,现在登录第一次文件ajax.php没有执行,我必须运行第二次代码来执行ajax.php中的php代码。

我用firebug尝试了源代码,发出了ajax请求,控制台显示了这一行:

GET http://localhost/myproject/news_update/ajax.php?rep=1+Aug+2010+to+31+Jul+2011  302 Found 5ms

这个错误是什么?

首先确保浏览器没有缓存响应,而是实际使用以下代码片段进行ajax调用:

$.ajaxSetup({ cache: false });

然后,请理解.change不会立即触发,它只有在与选择元素交互并改变值时才会触发。如果您希望它立即启动,您可以这样做:

$('#report').on('change', function() {
    var report = $('#report').find(':selected').text();
    $.get("ajax.php", {'rep':report}, function(data,status){
        alert("Data: " + data + "'nStatus: " + status);
    });
}).trigger('change'); // trigger change event right away