0

如果在查询字符串中设置了某些参数,我正在尝试在页面加载时在我的页面上提交表单。表单使用 ajax 提交并且工作正常,查询字符串中表单字段的预填充也很好,但无论我尝试自动提交表单,我最终都会陷入页面加载的无限循环。

PHP

// top of page
<?php
    if (isset($_GET['postcode'])) {
        $postcode = trim($_GET['postcode']);
    } else {
        $postcode = '';
    }

    if (isset($_GET['phone_num'])) {
        $phone_num = trim($_GET['phone_num']);
    } else {
        $phone_num = '';
    }
?>

jQuery

/* 
// causing infinite page loads
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
    $('#check').trigger("click");
    return false;
}
*/

$('form').submit(function() {
    $.get("script.php", $(this).serialize(), function(data){
        // process results
    }, "json");      
    return false;
});

HTML

<form class="navbar-form pull-right" action="" method="get">
    <input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
    <input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
    <button type="submit" class="btn btn-primary" id="check">Check</button>
</form>

而不是使用click自动表单提交的功能,我尝试做同样的事情,$('form').submit但我遇到了同样的问题。我希望页面能够正常运行,因此如果设置了参数,那么将自动进行 ajax 调用,但显然情况并非如此。

4

4 回答 4

1

在绑定提交事件之前,您将退出代码。删除return falseif 语句中的 if 语句,然后将 if 语句移到提交绑定之后。

$('form').submit(function() {
    $.get("script.php", $(this).serialize(), function(data){
        // process results
    }, "json");      
    return false;
});

if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
    $('#check').trigger("click");
    //return false;
}
于 2013-07-23T14:11:06.550 回答
1

HTML

<form class="navbar-form pull-right" action="" method="get">
    <input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
    <input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
    <input type="button" class="btn btn-primary" id="check">Check</button>
</form>

jQuery

$('#check').click(function(e) {
    e.preventDefault();
    $.get("script.php", $('form').serialize(), function(data){
        // process results
    }, "json");      
    return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
    $('#check').trigger("click");
}

使用submit按钮时,您正在执行默认事件(提交表单)以及处理.click()事件的处理程序。为避免这种情况,请使用e.preventDefault();仅导致事件的脚本部分进行处理。

于 2013-07-23T14:11:15.963 回答
1

尝试这样的事情:

if($('input[name="phone_num"]').val() && $('input[name="postcode"]').val()) {
    $('form').submit(function() {
        $.get("script.php", $(this).serialize(), function(data){
            // process results
        }, "json");      
        return false;
    }).submit();
}
于 2013-07-23T14:13:25.550 回答
1

在您的代码中使用这一行。

$('form').trigger("submit");
于 2013-07-23T14:13:33.927 回答