3

以下のフォームでは、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。検索ワードごとに延々と続きます。

このすべてで元のURLhttp://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();
  }
});
4

4 に答える 4

2

それを行う方法はいくつかあります。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!
});
于 2013-01-01T09:30:41.187 に答える
0
​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
于 2013-01-01T09:29:41.460 に答える
0

それを行うには複数の方法があります。元の URL をグローバル変数に保存できないのはなぜですか (フォーム送信などの関数の外部に保持されます)。

送信したくない場合は、送信しているすべての GET パラメータを返す window.location.hash を使用できます。分割を使用すると、必要な正確なパラメーターを取得できます。それでも助けが必要な場合は、コードを投稿します。

于 2013-01-01T09:21:44.703 に答える
0

最速の解決策: このコードでwindow.locationが常に であるhttp://localhost/search/?mod=all場合、 と言う必要さえありませんvar locale = window.location。と言うだけvar locale = "http://localhost/search/?mod=all"で、問題を回避できます。

于 2013-01-01T09:25:11.140 に答える