Php 通过删除空GET变量和简化变量名来缩短URL
我正在一个网站上工作,该网站在提交获取表单后会生成一个URL。表单值作为变量数组传递,必须至少定义一个变量数组才能在数据库上进行搜索。我希望通过删除空表单元素来缩短URL,并通过简化变量名来使其更易于使用 目前,URL看起来是这样的(只是有更多的变量): 我的目标是让它看起来像这样:Php 通过删除空GET变量和简化变量名来缩短URL,php,forms,yii,get,Php,Forms,Yii,Get,我正在一个网站上工作,该网站在提交获取表单后会生成一个URL。表单值作为变量数组传递,必须至少定义一个变量数组才能在数据库上进行搜索。我希望通过删除空表单元素来缩短URL,并通过简化变量名来使其更易于使用 目前,URL看起来是这样的(只是有更多的变量): 我的目标是让它看起来像这样: <form method="get" action="/example/search"> <input type="text" name="name" value="lorem ipsu
<form method="get" action="/example/search">
<input type="text" name="name" value="lorem ipsum">
<button type="submit">Search</button>
</form>
为了做到这一点,我有以下问题:
- 我已经读到,在使用GET方法时,仅用PHP无法删除空表单元素,因为这是html表单的标准行为。有没有办法通过yii的urlManager实现这一点
- 我是否可以在不更改变量名的情况下(例如,使用正则表达式)将“FormName[name]”替换为“name”等较短的名称
- 最后但并非最不重要的一点是:“yt0=Search”意味着什么?我如何将其从URL中删除
任何帮助都将不胜感激。参数名称来自表单的字段“
名称”
属性
因此,要对name=lorem+ipsum
进行表单查询,输入必须如下所示:
<form method="get" action="/example/search">
<input type="text" name="name" value="lorem ipsum">
<button type="submit">Search</button>
</form>
搜寻
你应该看看
name
属性,我猜它们是由你用来创建代码的代码生成的?空查询参数来自表单中的其他输入字段。如果要完全控制查询字符串,请手动创建表单。我建议您使用以下解决方案:
首先,您需要使用POST方法定义html表单:
<form method="post" action="/example/getSearchTerms">
<input type="text" name="name" value="lorem ipsum">
<button type="submit">Search</button>
</form>
然后,您需要定义主要搜索操作:
public function search($name)
{
//do search operation here.
}
最后,您需要添加url管理器规则:
"example/search/<name>"=>"example/search"
“示例/搜索/”=>“示例/搜索”
在此解决方案中,
getSearchTerms
操作负责接收用户输入的文本,然后将值传递给搜索操作。现在您的url可以是http://localhost/example/search/sampleText
。注意:如果愿意,可以跳过添加url管理器规则。在这种情况下,您的url必须类似于http://localhost/example/search/name/sampleText
。事实上,我们可以通过添加url管理器规则从url中删除“名称”部分 简单方法,如果jQuery是一个选项:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$('form').submit(function() { // ## Clean GET on Submit
$('form input').each(function() { // ## Check each Input
if ($(this).val().length == 0) { // ## If Empty
$(this).attr('disabled', true); // ## Disable Input
}
});
});
})(jQuery);
</script>
(函数($){
$('form').submit(函数(){/###Clean GET on submit
$('form input')。每个(function(){/###检查每个输入
if($(this.val().length==0){/##if为空
$(this.attr('disabled',true);//##禁用输入
}
});
});
})(jQuery);
谢谢您的回答,但是GET是应用程序的一项要求,我无法更改它。将$('form')
和$('form input')
替换为$('.cleanthiscoss')
和$('cleanthiscoss input')
以仅针对具有特定类的表单。
$('#your-form').submit(function () {
var data = $(this).serializeArray().filter(function (item) {
return !!item.value;
});
var param = jQuery.param(data);
window.location = this.action + (param ? "?" + param : "");
return false;
});