提交表单而不重新加载页面

But*_*ode 25 javascript form-submit

我有一个用JavaScript构建的函数,我希望在表单提交被执行后执行.它基本上完全改变了页面的外观.但我需要搜索框中的变量才能继续使用JavaScript.此刻它会闪烁并重置那里的内容,因为它会重新加载页面.

所以我在我的函数中设置了一个返回false,这使得它不会这样做,但我想要的变量不会通过表单提交.关于我应该怎么做才能得到它的任何想法?只要该updateTable()功能有效,页面就可以刷新,并且页面重置不会重置.

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

这是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;
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ant 33

你不能使用正常方式使用表单.相反,你想使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在JQuery上使用AJAX +1 (6认同)
  • <form action =""method ="get"onsubmit ="updateTable(); return false;">这将只执行javascript函数而不重新加载页面 (4认同)
  • ^非常方便我们这些人在嵌入式系统上做页面. (2认同)

Ahs*_*hah 29

您可以使用jQuery序列化函数以及get/post,如下所示:

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

$.post('server.php', $('#theform').serialize())
Run Code Online (Sandbox Code Playgroud)

jQuery Serialize Documentation: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.
});
Run Code Online (Sandbox Code Playgroud)

  • 问题是没有标记jQuery,虽然`serialize()`非常简洁. (3认同)
  • 为什么要downvote?我看到人们一直在发布jQuery答案,即使jQuery没有被标记... (3认同)
  • @AhsanShah还有其他框架.也许(也可能)OP正在学习Javascript,并想知道应该如何完成. (3认同)