33

フォーム送信がヒットした後に実行したい JavaScript に組み込まれた関数があります。基本的に、ページの外観を完全に変更します。しかし、JavaScript を通過するには、検索ボックスからの変数が必要です。現時点では、ページをリロードするため、点滅してそこにあったものがリセットされます。

そのため、関数に return false を設定して、それを行わないようにしていますが、必要な変数がフォームから送信されません。それを得るために何をすべきかについてのアイデアはありますか?updateTable()機能が動作し、ページのリセットによってリセットされない限り、ページが更新されても問題ありません。

<form action="" method="get" onsubmit="return updateTable();">
  <input name="search" type="text">
  <input type="submit" value="Search" >
</form>

これはupdateTable機能です:

function updateTable() { 
  var photoViewer = document.getElementById('photoViewer');
  var photo = document.getElementById('photo1').href;
  var numOfPics = 5;
  var columns = 3; 
  var rows = Math.ceil(numOfPics/columns);
  var content="";
  var count=0;

  content = "<table class='photoViewer' id='photoViewer'>";
  for (r = 0; r < rows; r++) {
    content +="<tr>";
    for (c = 0; c < columns; c++) {
      count++;
      if(count == numOfPics) break; // check if number of cells is equal number of pictures to stop
      content +="<td><a href='"+photo+"' id='photo1'><img class='photo' src='"+photo+"' alt='Photo'></a><p>City View</p></td>";
    }
    content +="</tr>";
  }
  content += "</table>";
  photoViewer.innerHTML = content;
}
4

4 に答える 4

49

通常の方法でフォームを使用してこれを行うことはできません。代わりに、AJAX を使用します。

データを送信し、ページの応答を警告するサンプル関数。

function submitForm() {
    var http = new XMLHttpRequest();
    http.open("POST", "<<whereverTheFormIsGoing>>", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}
于 2013-08-11T08:07:09.563 に答える
36

次のように、get/post とともに jQuery シリアル化関数を使用できます。

$.get('server.php?' + $('#theForm').serialize())

$.post('server.php', $('#theform').serialize())

jQuery シリアル化のドキュメント: http://api.jquery.com/serialize/

jQuery を使用した単純な AJAX 送信:

// this is the id of the submit button
$("#submitButtonId").click(function() {

    var url = "path/to/your/script.php"; // the script where you handle the form input.

    $.ajax({
           type: "POST",
           url: url,
           data: $("#idForm").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    return false; // avoid to execute the actual submit of the form.
});
于 2013-08-11T08:08:43.007 に答える
-2

自分がやりたかったこととは違う方法でやった...必要な結果が得られた. フォームを送信するのではなく、テキスト フィールドの値を取得して JavaScript で使用し、テキスト フィールドをリセットすることにしました。この質問で誰かを悩ませたらごめんなさい。

基本的にこれを行いました:

    var search = document.getElementById('search').value;
    document.getElementById('search').value = "";
于 2013-08-11T09:21:57.160 に答える