带有表单的自定义URL

Custom URL with form

本文关键字:自定义 URL 表单      更新时间:2023-09-26

我正在开发codeigniter,并且有一个搜索栏,我想将其映射到控制器中的搜索类。当前URL为search/searchterm。我想构建一个遵循这一点的表单,并且实际上只需要获取表单中的任何内容并将其传递到URL。我试着在提交时做一个javascript重定位,如下所示:

document.location.href= "<?= base_url() ?>" + document.forms["searchbox"]["search"].value

但它似乎不起作用。对于这样的东西,你们推荐什么是最好的?我相信很多人在他们的项目中都需要类似于我想要的东西。

这是另一个示例。它是一个有效的xhtml文档,可以在谷歌中搜索您在搜索框中键入的任何内容。它适用于FF10、IE8、Chrome 17和Opera 11.61。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Search</title>
    <script type="text/javascript">
        window.onload = function(){
            var form = document.getElementById("form1");
            form.onsubmit = function(){
                var searchText = document.getElementById("searchText");
                window.location = "http://www.google.com/search?q=" + searchText.value;
                return false;
            };          
        };
    </script>
</head>
<body>
    <form id="form1" method="post" action="">
        <div>
            <label for="searchText">Search:</label>
            <input type="text" id="searchText" name="searchText" />
            <input type="submit" value="Click" />
        </div>
    </form>
</body>
</html>

如果它不在表单中,这将起作用,要在表单中执行此操作,您需要设置onsubmit事件来为表单设置适当的操作。

下面是一个简单的工作示例:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script type="text/javascript">
        function foo() {
            document.forms["searchbox"].action= window.location.href+"/" + document.forms["searchbox"]["search"].value; 
            return true; 
        }
    </script>
</head>
<body>
    <form  id="searchbox" onsubmit="foo()" > 
        <input type="text" id="search" />
        <input type="submit" />
    </form>
</body>
</html>