【问题标题】:jQuery - Submit Form to RESTful URLjQuery - 提交表单到 RESTful URL
【发布时间】:2016-10-04 10:09:06
【问题描述】:

对此,我的大脑 100% 一片空白,所以需要一些指导。

<form action="/" id="searchForm">
  <input type="text" name="s" placeholder="Search...">
  <input type="submit" value="Search">
</form>

我需要该表单,以便页面重定向到一个 URL,例如

http://example.com/rest/ful/url/{value of search}/ 例如http://example.com/rest/ful/url/jQuery/ 如果我搜索 jQuery

我什至需要 jQuery 吗?

【问题讨论】:

    标签: javascript jquery rest


    【解决方案1】:

    用 jquery 解决:

    $('#searchForm').on('submit', function(event){
        $('[name=s]').prop('disabled', true)
        $(this).attr('action', 'http://example.com/rest/ful/url/' +     $('[name=s]').val());
    });
    

    https://jsfiddle.net/3y4efht0/1/

    【讨论】:

      【解决方案2】:

      使用jquery的.submit事件获取输入值,使用window.location.href实现你的需求。

      请检查下面的sn-p。

      $("#searchForm").submit(function( event ) {
        var searchTerm = $("input[name='s']").val();
        if($.trim(searchTerm)!=""){
          var redirectURL = "http://example.com/rest/ful/url/"+$.trim(searchTerm)+"/";
          console.log(redirectURL);
          window.location.href=redirectURL;
        }else{
          alert("Please enter search term!");
        }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <form action="/" id="searchForm">
        <input type="text" name="s" placeholder="Search...">
        <input type="submit" value="Search">
      </form>

      【讨论】:

        【解决方案3】:

        您不需要 jquery 来执行此操作,但它可以提供帮助,您必须侦听提交事件,防止默认行为并重定向到您想要的页面:

        $('#searchForm').on('submit', function(e){
            e.preventDefault();
            document.location.href = 'http://example.com/rest/ful/url/'+$('#s').val()+'/'
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-04-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多