检索与jQuery AJAX的数据,而无需刷新页面 [英] Retrieving Data with jQuery AJAX Without Reloading Page

查看:182
本文介绍了检索与jQuery AJAX的数据,而无需刷新页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个jQuery的AJAX code,从一个MySQL数据库中检索数据。它的工作原理无需重新加载页面,问题是,它只能在第一时间。如果我再次提交表单,那么整个页面重新加载。我怎样才能让这样我就可以提交表单多次和检索数据,而无需重新加载页面?

jQuery的

  $(文件)。就绪(函数(){
    $('表')。在('改变',函数(){
        $(本).closest(形式)提交();
    });

    $('表')。在('提交',函数(事件){
        。事件preventDefault();
        $阿贾克斯({
            网址:$(本).attr(行动),
            类型:$(本).attr(方法),
            数据:$(本).serialize()
            成功:功能(数据){$(形式)HTML(数据); }
        });
    });
});
 

HTML

 <形式的行动=form.php的方法=后ID =汽车与GT;
    <选择名称=ID>
        <期权价值=>选择...< /选项>
        <期权价值=1< PHP的echo(使用isset($ ID),并且$ id == 1)? 选择':'';>>雪佛兰< /选项>?
        <期权价值=2< PHP的echo(使用isset($ ID),并且$ id == 2)? 选择':'';>>福特< /选项>?
        <期权价值=3< PHP的echo(使用isset($ ID),并且$ id = = 3)? 选择':'';>>道奇< /选项>?
    < /选择>
< /形式GT;
 

解决方案

请不要使用提交,而是使用变更功能

 <脚本类型=文/ JavaScript的>
$(文件)。就绪(函数(){
    $('表')。在('改变',函数(){
        $阿贾克斯({
            网址:form.php的,
            类型:'后',
            数据:{ID:jQuery的('选择[名称= ID])VAL()},
            成功:功能(数据){$(形式)HTML(数据); }
        });
    });
});
< / SCRIPT>
 

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>

解决方案

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>

这篇关于检索与jQuery AJAX的数据,而无需刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆