2016-10-04 71 views
-1

我的思想已經100%空白,所以需要一些指導。jQuery - 提交表單到RESTful URL

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

回答

1

使用.submit的jQuery的事件,並獲取輸入值,用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>

1

你並不需要jQuery來做到這一點,但它可以幫助,你要聽的提交事件,阻止默認行爲,並重定向到該頁面你想要的:

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