当URL中存在查询字符串时,Jquery表单提交无法工作


Jquery form submit not working when query string is present in URL

测试场景:

  1. 在文本框中键入"你好",您应该会看到页面中写着"你好"
  2. 现在单击"测试"链接(它只是一个指向自身的链接,带有查询字符串&test=1
  3. 现在在文本框中键入"世界",你可以看到它不再写在页面中

为什么会发生这种情况?

您可以在.php页面上测试此页面:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
    <form id="search_form" method="post">
        <label for="search">Search:</label>
        <input type="search" id="search" />
    </form>
    <script type="text/javascript">
        $('#search_form').submit(function (event) {         
            window.location.href = '<?=$_SERVER['PHP_SELF'].'?s='?>' + $('#search').val();
            event.preventDefault();
        });
    </script>   
    <br /><br />
    <?php $s = filter_input(INPUT_GET, 's'); ?>
    Query string: <?=$s?>
    <br /><br />
    <a href="<?=$_SERVER['PHP_SELF']?>?s=<?=$s?>&test=1">test</a>
</body>
</html>

演示URL:(在问题解决后删除)

由于您使用的是Jquery Mobile,默认情况下所有链接都是通过AJAX执行的。这会混淆你的脚本。我建议在链接中抑制这一点。

<a href="<?=$_SERVER['PHP_SELF']?>?s=<?=$s?>&test=1" data-ajax="false">test</a>

这将允许链接被正常处理,并将在没有AJAX的情况下执行URL。