在本例中,使用jquery获取原始url

Get the original url in this case with jquery

本文关键字:jquery 获取 原始 url 使用      更新时间:2023-09-26

在下面的表单中,我更改了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