我想使用JavaScript来更改表单的操作,这样我就可以在同一个表单中使用不同的提交输入,链接到不同的页面。
我还遇到了一个问题,就是使用Apache rewrite将example.com/page-name
更改为example.com/index.pl?page=page-name
。我发现更改表单的操作会导致example.com/index.pl
(没有页面参数)被渲染,尽管预期的URL(example.com/page-name
)显示在地址栏中。
为了解决这个问题,我使用JavaScript插入了一个隐藏字段来设置页面参数。我仍然更改了表单的操作,只是为了使地址栏显示正确的URL。
function setAction (element, page)
{
if(checkCondition(page))
{
var input = document.createElement("input");
input.setAttribute("type","hidden");
input.setAttribute("name","page");
input.setAttribute("value",page);
element.form.appendChild(input);
element.form.action = '/' + page;
element.form.submit();
}
}
在表单中:
<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />
以下是我的Apache重写规则:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}
我很想知道为什么仅仅设置操作(action)不起作用,欢迎解释。
document['search-theme-form']
,document.search-theme-form
实际上不起作用。 - gen_Ericdocument.forms.search-theme-form.action
是有效的。 - zhuxiaoxi