Retrieving Data with jQuery AJAX Without Reloading Page

痴心易碎 提交于 2019-12-11 14:27:39

问题


I have this jQuery AJAX code that retrieves data from a MySQL database. It works without reloading the page, the problem is that it only works the first time. If I submit the form again, then the whole page reloads. How can I make it so I can submit the form multiple times and retrieve the data without reloading the page?

jQuery

$(document).ready(function() {
    $('form').on('change', function() {
        $(this).closest('form').submit();
    });

    $('form').on('submit', function(event) {
        event.preventDefault();
        $.ajax({
            url: $(this).attr('action'),
            type: $(this).attr('method'),
            data: $(this).serialize(),
            success:function(data) { $('form').html(data); }
        });
    });
});

HTML

<form action="form.php" method="post" id="cars">
    <select name="id">
        <option value="">Selection...</option>
        <option value="1" <?php echo (isset($id) and $id == 1) ? 'selected' : '';?>>Chevy</option>
        <option value="2" <?php echo (isset($id) and $id == 2) ? 'selected' : '';?>>Ford</option>
        <option value="3" <?php echo (isset($id) and $id == 3) ? 'selected' : '';?>>Dodge</option>
    </select> 
</form>

回答1:


Please do not use submit, instead use change function

<script type="text/javascript">
$(document).ready(function() {
    $('form').on('change', function() {
        $.ajax({
            url: 'form.php',
            type: 'post',
            data: {'id':jQuery('select[name=id]').val()},
            success:function(data) { $('form').html(data); }
        });
    });
});
</script>


来源:https://stackoverflow.com/questions/28123315/retrieving-data-with-jquery-ajax-without-reloading-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!