在本例中,使用jquery获取原始url
Get the original url in this case with jquery
在下面的表单中,我更改了action属性并提交了表单。这很好。情况是:如果当前位置是http://localhost/search/?mod=all
,搜索词是14,则操作将更改为http://localhost/search/?mod=all&handle=14
,浏览器中的url也将更改为。
但下次我尝试搜索时,由于url现在是http://localhost/search/?mod=all&handle=14
,我得到了http://localhost/search/?mod=all&handle=14&handle=15
。它会在每个搜索词中持续不断。
知道我如何通过这一切保留原始url http://localhost/search/?mod=all
吗。
这是表格:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
这是jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
有几种方法可以做到这一点。我宁愿不处理window.location,而是做一些更简单的事情:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
有多种方法可以做到这一点。为什么不能将原始URL存储在全局变量中(保存在表单提交等函数之外(
如果你不想这样做,你可以使用window.location.hash,它将返回你正在发送的所有GET参数。使用split,您将能够获得所需的精确参数。如果你仍然需要帮助,我会发布代码。
最快的解决方案:如果对于此代码,window.location
应该始终是http://localhost/search/?mod=all
,那么您甚至不需要说var locale = window.location
。只要说var locale = "http://localhost/search/?mod=all"
就可以避免问题。
var s = window.location.hostname; // gets the hostname
var d = window.location.protocol; // gets the protocol
var g = window.location.search; // gets all the params
var x = g.split("&"); // split each parameter
var url = d+"//"+s+x[0]; // makes url you want
alert(url); // just for chill
- 使用jQuery获取Dropzone实例/对象
- 如何使用javascript/jquery获取iframe的URL的锚点属性
- 使用Javascript/JQuery获取JSON GET数据
- jQuery获取父元素并将其隐藏
- JavaScript/jQuery-获取当前元素的跨度值
- 使用 jquery 获取外部父 UL
- 当两个单独的单词被放在目标上时,使用Jquery获取一个值
- 如何使用jquery获取Json的节点
- 使用 jQuery 获取样式属性值
- JQuery获取隐藏字段的值
- 使用jQuery获取Facebook视频ID
- 使用jQuery获取第N个元素的数据属性值
- Jquery获取请求Uri太长
- jQuery:获取点击的按钮值
- 如何通过javascript或jquery获取下一行列
- 根据列表元素的值使用JQuery获取列表元素
- 使用jQuery获取选择列表中每个更改的值
- 使用jQuery获取用户坐标
- jquery获取多个选择框的值作为数组
- 如何使用JavaScript/JQuery获取下拉列表的选定值