提交不带查询字符串的表单

Submit a form without query string

我在类似 http://example.com?query=value 的页面上,它具有 <form id="formId" method="POST"> 的形式。

在没有查询字符串的情况下将表单提交到 http://example.com 的最佳方法是什么?

我目前正在尝试:

$('#formId').submit(function(e){
    e.preventDefault();
    var url = window.location.href; 
    if (url.indexOf("?") != -1){
        $('#formId').attr('action', url.split("?")[0]);
    }
    $('#formId').submit();
});

但它似乎不起作用。

我更喜欢 javascript/jQuery 解决方案,因为这种模式在网站上很常见

与其尝试更改提交时的操作,不如查找没有 action 属性的表单并适当设置它们,例如

jQuery(function($) {
    $('form:not([action])').attr('action', location.pathname);
});

对于其他看这里的人来说,一个快速而肮脏的解决方案是将表单操作属性设置为“?”。例如:

<form id="formId" method="POST" action="?">

这将 post 对当前 url 的请求,查询字符串只是一个“?”

虽然这没有使用 javascript,但它可能不是 OP 想要的答案。