如何删除? (问号) from url 后面没有跟任何参数?

How to remove ? (question mark) from url when it is not followed by any parameters?

我有一个向服务器发送获取请求的表单。输入参数以 QueryString 形式发送到服务器。

这是我的表格:

<form action="host-name/Home/Browse"  onsubmit="removeEmptyParameters()">
    <input type="text" name="Term" /> 
    <input type="text" name="Address" /> 
    <input type="submit" value="submit">
</form>

在提交表单之前,执行以下JavaScript方法以从表单中删除空输入参数:

function removeEmptyParameters() {
    // set the name attribute = "" for empty inputs, so they won't be posted to server
    $('form').find('input').each(function () {
        if (this.value === "") {
            $(this).attr('name', '');
        }
    });
}

所以如果用户输入一些内容,请求将是:

ulr: host-name/Home/Browse?Term=some-term&Address=some-address

如果所有的输入都是空的,下面的url被发送到服务器:

ulr: host-name/Home/Browse?

这很好用,但我想从 url 中删除 ?,这样它就干净了。可以这样做吗?

您可以使用 String.prototype.slice() 方法来实现此目的。如果 url 的最后一个字符是“?”,您可以将其从 url 字符串中删除。

let url = "www.someurl.com?";
let length = url.length;
if(url.charAt(length-1)==='?')
url=url.slice(0,length-1);
console.log(url);

有关 slice() 的更多详细信息,请访问以下 MDN link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice

我不确定这是否是最佳解决方案,但您可以尝试使用 window.location.href 重定向以防参数为空。这样,就可以保持 url 干净。

您可以像这样重写代码。

使用这种方法,您的浏览器 URL 不会根据表单值动态更改,并且您的 URL 看起来很干净。

并且您还可以使用 jquery 库(因为您的代码已经使用 jquery 编写)使用 ajax 提交表单,您可以在其中动态修改表单URL 基于输入数据。这样你就有了更多的控制权。

<html>

<head>
  <script src="https://code.jquery.com/jquery-3.4.1.min.js"
    integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
    </script>

  <head>

  <body>
    <!-- Replace with your hostname instead of https://eniuu7vo8sak.x.pipedream.net -->
    <form method="GET" onsubmit="return handleSubmit('https://eniuu7vo8sak.x.pipedream.net/Home/Browse')">
      <input type="text" name="Term" />
      <input type="text" name="Address" />
      <input type="submit" value="submit">
    </form>

    <script>

      function handleSubmit(url) {
        removeEmptyParameters();
        const formData = $('form').serialize();
        console.log(formData);
        // Only adds the question mark to the url only if there are some input data.
        if (formData) {
          url = `${url}?${formData}`;
        }
        $.get(url);
        return false;
      }

      function removeEmptyParameters() {
        // set the name attribute = "" for empty inputs, so they won't be posted to server
        $('form').find('input').each(function () {
          if (this.value === "") {
            $(this).attr('name', '');
          }
        });
      }            
    </script>

  </body>

</html>