javascript - 使用JQuery刷新页面但没有得到想要的结果

标签 javascript php jquery html

我正在使用 Jquery 刷新页面,它正在刷新,但是当我从类别中选择一个选项时,它会刷新,然后我选择的类别消失,但我希望当我选择任何一个选项时,页面都会刷新,但我选择的选项也将与我选择的相同,希望你们能理解我的问题。

$(function() { $('select[name="cat"]').change(function() { location.href = 'insert_book.php?cat=' + $(this).find('option:selected').val(); }); });
    <select id="rf" name="cat">
                    <option value='null'>Select your Desire</option>
                    <?php
                    include('includes/db.php');
                    $c_query="select * from categories";
                    $c_run=(mysql_query($c_query));
                    while($c_row=mysql_fetch_array($c_run)){
                        $c_id=$c_row['p_id'];
                        $c_title=$c_row['p_title'];
                        echo "<option value='$c_id'>$c_title</option>";
                        }
                    ?>
                </select>

最佳答案

将刷新代码更改为:

$(function() {
    $('select[name="cat"]').change(function(ev) { 
        location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val(); 
    }); 
});

Also move this JS code after the HTML code for the select element or wrap it with $(document).ready() like this:

$(document).ready(function(){
    $('select[name="cat"]').change(function(ev) { 
        location.href = 'insert_book.php?cat=' + $(ev.currentTarget).val(); 
    }); 
});

Now in the loop code:

$selectedCategory = array_key_exists('cat', $_GET) ? $_GET['cat'] : 0;
while($c_row=mysql_fetch_array($c_run)){
    $c_id=$c_row['p_id'];
    $c_title=$c_row['p_title'];
    echo "<option value='$c_id'".($selectedCategory == $c_id ? " selected='selected'" :"").">$c_title</option>";
}

最后:

正如 Chris Baker 提到的,停止使用 mysql_ 并使用 mysqli_PDO

关于javascript - 使用JQuery刷新页面但没有得到想要的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26916874/

相关文章:

javascript - 从 Telerik 切换到 Kendo UI 缺少​​ orderBy 和 filter By

javascript - 无法让 PHP 在 HTML 中的 &lt;textarea&gt; 标记内执行

PHP 传递数组作为引用

php - 有没有办法隐藏所有数据库信息,如密码、用户名等?

php - array_search 函数不返回值

javascript - 数据属性不适用于动态添加的 li 元素

Javascript slider : How to set default opacity on page load

javascript - IE8 HTML5 动态内容没有应用 AngularJs 的样式

javascript - 在 jQuery 中全局使用变量

javascript - Highcharts 中柱形图的带有 url 属性的钻取功能