【问题标题】:Form submitting with GET method and location.hash value使用 GET 方法和 location.hash 值提交表单
【发布时间】:2015-02-10 22:38:43
【问题描述】:

有一个带有 method="get" 的 html 表单,没有带有 type="submit" 的操作和按钮

    (function(){
        jQuery(".time").text(Date.now());
    })();
    jQuery(".set-hash").on("click", function () {
        location.hash = "hash";
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get">
    <div class="time"></div>
    <input type="text" name="param">
    <button type="submit">Submit</button>
    <button type="button" class="set-hash">Set Hash</button>
</form>

案例 1。

  • 点击提交按钮。

查看请求已发送。

案例 2。

  • 点击设置哈希按钮
  • 点击提交按钮

查看请求未发送。没有任何改变。

案例 3。

  • 点击设置哈希按钮
  • 为参数输入设置任何值
  • 点击提交按钮
  • 将任何其他值设置为参数输入
  • 点击提交按钮

请注意,仅当参数更改时才发送请求。

所以问题是:为什么只有在参数改变时才发送请求?

P。 S.

当将方法从 GET 更改为 POST 时,一切正常。但是我需要地址栏中的请求参数。

【问题讨论】:

  • 尝试在表单中添加"" 以外的操作。
  • 试过了,没用。看起来它与 location.hash 有关系

标签: javascript html forms


【解决方案1】:

它在这里工作试试这个。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Doc title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function(){
        jQuery(".time").text(Date.now());
        var url = window.location.href;
        jQuery(".url").text(url);
        jQuery(".set-hash").on("click", function () {
                  location.hash = "hash";
                 // alert("test");
        });

});
</script>
</head>
<body>
<form method="get">
    <div class="time"></div>
    <input type="text" name="param">
    <button type="submit">Submit</button>
    <button type="button" class="set-hash">Set Hash</button><br />
    Current URL:<div class="url"></div>
</form> 
</body>
</html> 

【讨论】:

  • 谢谢,但有什么区别?我只看到添加了 .url 操作。
  • 检查您的脚本。我认为,括号的顺序不正确。您的函数过去常常在调用 date() 后终止
  • 已检查,不起作用 :( 设置哈希时 - 时间不会改变
  • 您是否保留了日期并在就绪函数中单击 func ?它应该可以工作。
  • 是的,这两个函数都在就绪函数中。 Chrome last + win7,Firefox last + win7,不起作用
【解决方案2】:

还没找到原因。

似乎问题与浏览器以某种特殊方式处理的锚点有关。当我更改 location.host 浏览器尝试跳转到添加的锚点。不知何故,这会影响提交按钮的处理。

不得不使用解决方法 - 将哈希中的数据存储在 localStorage 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-10
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多