jquery(ajax)单击使php脚本多次运行

时间:2015-09-17 08:55:52

标签: javascript php jquery html ajax

我有一个按钮,当点击它时,它呈现(在ajax的帮助下),php脚本的内容(基本上它是一个联系表单)。我的问题是,当单击该按钮时,这将调用php脚本两次或更多次。我尝试了很多解决方案,但都没有。

HTML

<ul class="nav navbar-nav navbar-right">
    <li><a href="" id="contact">CONTACT</a></li>
</ul>

的JavaScript

$(document).ready(function(){
    $('#contact').off();
    // the above line I've replaced it with:
    // 1. $('#contact').off('click');
    // 2. $('#contact').unbind();
    // 3. $('#contact').unbind('click');
    $('#contact').click(function(e){
        $.ajax({
            type: "POST",
            url: "contact.php",
            success: function(html){
                $('#content').html(html);
            }
        });
        e.preventDefault();
    });
});

运行包含HTML和JS的页面时得到的响应:

enter image description here

contact.php接收使用ajax发送的数据(来自index.php - 包含上述代码的页面),然后将新联系人发送到另一个PHP脚本(这是一个类),该脚本存储新联系人在数据库中,并返回(给contact.php)一个响应。

contact.php

<form id="form">
    <div class="form-group col-xs-12 col-md-4">
        <input type="text" class="form-control" id="nume" value="<?php echo Escape::esc($nume);?>" style="pointer-events:none;background:#EFEFEF;"/>
    </div>
    <div class="col-xs-12"></div>
    <div class="form-group col-xs-12 col-md-4">
        <input type="text" class="form-control" id="prenume" value="<?php echo Escape::esc($prenume);?>" style="pointer-events:none;background:#EFEFEF;"/>
    </div>
    <div class="col-xs-12"></div>
    <div class="form-group col-xs-12 col-md-10">
        <textarea class="form-control" id="mesaj" rows="20" data-toggle="mesaj" data-placement="bottom" title="Va rog introduceti mesajul dvs."></textarea>
    </div>
    <div class="col-xs-12"></div>
    <div style="clear:both"></div>
    <button class="btn btn-default" onclick="return validate();" style="margin-left:15px;">TRIMITE</button>
</form>
<script type="text/javascript">
function validate(){
    var nume    = $('#nume').val();
    var prenume = $('#prenume').val();
    var mesaj   = $('#mesaj').val().trim();

    if (mesaj == '' || mesaj.length < 3){
        $(function(){
            $('[data-toggle="mesaj"]').tooltip();
            document.getElementById('mesaj').focus();
        });
        return false;
    }
    $('#form').off();// here I tried to unbind all the previous submit events too
    $('#form').on('submit',function(e){
        $.ajax({
            type: "POST",
            url: "../../app/classes/Contact.php",
            data: {nume:nume, prenume:prenume, mesaj:mesaj},
            success: function(html){
                $('#content').html(html);
            }
        });
        e.preventDefault();
    });
}
</script>

欢迎任何提示!谢谢!

0 个答案:

没有答案