【问题标题】:HTML Form element to URLHTML 表单元素到 URL
【发布时间】:2012-07-23 12:42:52
【问题描述】:

我正在使用使用不同搜索方法的电子商务引擎脚本。

而不是像这样使用 GET 的 URL:

http://search.com/searchc?q=the+query

它使用

http://search.com/searchc/the+query

我如何制作一个 POST 或 GET 表单,因为这个表单会生成 URL

http://search.com/searchc/?q=the+query


<form action="/searchc/" method="post">
    <input type="text" id="q" name="q">
    <input type="submit" value="go">
</form>

也试过这个(get 或 post 对这两个都不起作用)

<form action="/searchc/" method="post">
    <input type="text" id="" name="">
    <input type="submit" value="go">
</form>

【问题讨论】:

    标签: html forms url post get


    【解决方案1】:

    可靠的方法有两个组件:客户端 JavaScript 操作,它根据需要将表单提交转换为请求,以及(作为非 JS 情况的备份)一个简单的服务器端重定向实用程序,它接收来自表单的请求并将其重定向为已修改。

    类似这样的东西(对于 GET 案例):

    <form action="http://www.example.com/redirect"
      onsubmit="location.href = document.getElementById('f1').value + 
      document.getElementById('q').value; return false">
    <input type="text" id="q" name="f2">
    <input type="submit" value="go">
    <input type=hidden id=f1 name=f1 value="http://search.com/search/">
    </form>
    

    这里的http://www.example.com/redirect 是一些服务器端表单处理程序,它只读取表单字段并选取名为 f1、f2、...的字段,将它们连接成一个字符串,并将其用作 URL 进行重定向。作为一个 CGI 脚本,这将是

    use CGI qw(:standard);
    $dest = '';
    $i = 1;
    while(param('f'.$i)) {
       $dest .= param('f'.$i++); }
    print "Location: $dest\n\n";
    

    【讨论】:

      【解决方案2】:
      <form action="/searchc/" method="post" onsubmit="this.action+=this.q.value;return true">
         <input type="text" id="q">
         <input type="submit" value="go">
      </form>
      

      空格将提交为 %20

      你可以使用

      this.action+=this.q.value.split(' ').join('+')
      

      替换它们

      【讨论】:

        【解决方案3】:

        这是一个非常奇怪的 url 模式,但无论如何你都可以这样做:

        $(function () {
            $('form').submit(function () {
                var url = '/searchc/' + encodeURIComponent($(this).find('[name=q]').val());
                window.location = url;
                return false;
            });    
        });
        

        【讨论】:

          猜你喜欢
          • 2011-05-14
          • 1970-01-01
          • 2022-01-06
          • 2015-08-21
          • 2012-11-11
          • 2015-11-23
          • 1970-01-01
          • 2017-01-11
          • 1970-01-01
          相关资源
          最近更新 更多