jQuery -提交表单到RESTful URL

jQuery - Submit Form to RESTful URL

本文关键字:RESTful URL 表单 提交 jQuery      更新时间:2023-09-26

我脑子里一片空白,所以需要一些指导。

<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吗?

使用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/

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

请检查下面的代码片段。

$("#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>

你不需要jquery来做这件事,但它可以帮助你,你必须监听提交事件,防止默认行为并重定向到你想要的页面:

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