繁体   English   中英

将表单提交到同一页面而不重新加载

[英]Submitting a form to the same page without reloading it

我正在尝试使用Ajax发送表单而不刷新页面。 将表单提交到同一页面非常重要,这就是我使用url: 'customer-management?form_sent=yes'

HTML

<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">    
      <i onclick="$(this).closest(\'form\').submit()" id="' . $get_uncontacted_member->id . '" class="fa fa-phone-square called"></i>
</form>

JS

$('.called').click(function() {
    $.ajax({
        type: 'post',
        url: 'customer-management?form_sent=yes',
        data: $(this).attr('id');
        success: function(r) {
            alert(r);
        } 
    })
})

PHP

if (isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes') { return 'That worked!' }

页面重新加载,我想我做错了什么。

您没有正确传递数据。 由于您正在执行POST请求,因此不应将数据作为查询字符串传递。 而是通过data属性传递它。 另外,添加return false; 这样表格就不会提交。

$.ajax({
    type: 'post',
    url: 'customer-management',
    data: { form_sent: 'yes' },
    success: function(r) {
        alert(r);
    } 
});

return false;

您可以删除此代码:

onclick="$(this).closest(\'form\').submit()"

你必须return false; 从您的onclick甚至,否则浏览器将继续提交表单。

onclick="$(this).closest('form').submit(); return false;"

试试这个:

<form method="post">
            <i id="<?php echo $get_uncontacted_member->id; ?>" class="fa fa-phone-square called"></i>
    </form>
    <script>
            $('.called').click(function()
            {
                    $.ajax({
                            type   : 'post',
                            url    : 'customer-management',
                            data   : {form_sent: 'yes',id:$(this).attr('id')},
                            success: function(r)
                            {
                                    alert(r);
                            }
                    })
            });
    </script>

PHP:

    <?php
if(isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes')
{
        echo 'That worked!';
        exit;
}
?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM