【问题标题】:How to show the table on same page after submitting the form in html?html中提交表单后如何在同一页面上显示表格?
【发布时间】:2023-04-01 17:17:01
【问题描述】:

我有一个表单,它接受日期选择器作为输入并将该值发送到后端并根据输入获得一些响应。响应数据将被插入到表中。 提交表单后,它应该在同一页面上显示表格。

HTML:

<!DOCTYPE html>
<html>

<head>
  <title>
    Date Picker
  </title>

  <link href='https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/ui-lightness/jquery-ui.css' rel='stylesheet'>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
  </script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js">
  </script>
</head>

<body>
  <form method="POST">
    Date: <input type="text" id="my_date_picker">
    <button id="sbtn">Submit</button>

    <div id="mytable">
      <table id="datatable" style="display:none">

      </table>
    </div>
  </form>
  <script>
    $(document).ready(function() {

      $(function() {
        $("#my_date_picker").datepicker();
      });
    })
  </script>
</body>

</html>

JS

$("#sbtn").click(function() {
   if ($("#my_date_picker").val().length === 0){
         alert('Invalid');
         return false;
     }else {
       $("form").submit();
       $("#datatable").show();
     }
  });

提交表单后,我无法在此处显示表格。有没有办法在表单提交后在同一页面上显示表格?

谢谢。

【问题讨论】:

  • 当您提交表单时,页面将重新加载。因此,您的后端应该处理表单提交,使用数据表生成新的 html 响应并将其返回给浏览器。否则,您必须使用 ajax 将表单数据传递给支持者并获取结果,然后使用 javascript 在数据表中呈现结果。
  • @farhodius 你能用一个例子解释一下这两种方法吗?这将是一个很大的帮助。谢谢
  • @Thra 你是如何从服务器渲染它的?
  • @Athira V Ajit,使用 Python (render_template) 渲染 HTML 页面。
  • @Thra 所以我建议您可以重定向请求以让路由器重新呈现页面,以便将更新的表格显示给用户。

标签: javascript html jquery forms form-submit


【解决方案1】:

如果您在页面加载本身中获取数据,您可以在 ajax 提交后使用location.reload(),这将重新加载当前页面,或者您可以附加来自 ajax 响应的数据,有点像 $('#datatable').append(data);

【讨论】:

    【解决方案2】:

      document.getElementById("button").addEventListener("click", () => {
        const val = document.getElementById("data").value
        fetch('//url/to/post/the/data', {
          method: 'POST',
          headers: {
            // if any
          },
          body: JSON.stringify({
            data: val
            // or other data
          })
        })
        .then(res => res.json())
        .then(res => {
          // response from the backend
          // assuming the data will be array and that has to be displayed as table, something like this,
          // res = {
          //   data: [{name: 'Nikhil', age: '22'}, {name: 'Hello', age: '29'}]
          // }
          const arr = res.data
          // setting the headers
          let content = '<table><tr><th>Name</th><th>Age</th></tr>';
          // setting the rows of the table dynamically
          arr.forEach((ele) => {
            content += `<tr>`
            content += `<td>${ele.name}</td>`
            content += `<td>${ele.age}</td>`
            content += `</tr>`
          })
          // closing the table tag
          content += `</table>`
          // inserting the html generated in the div with the id - result
          document.getElementById('result').innerHTML = content;
        })
        .catch(err => {
          // handle error here
        })
      })
     
    <html>
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
    </head>
    <body>
    
      <!-- // form fields and submit button -->
      <input type="text" id="data">
      <button id="button">Submit</button>
    
      <!-- // table where data need to be displayed -->
      <div id='result'></div>
    
    </body>
    </html>

    其中一种可能的解决方案是,您可以使用fetchajax 从后端获取数据并将其显示为表格,而无需刷新页面。

    你可以在这里了解更多,

    AJAX - https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX

    获取 - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

    编辑:添加的代码解释了如何将 DOM 中的数据作为表格添加。

    PS:这是如何将数据添加为表格的可能解决方案之一,其他解决方案包括使用createTextNode()等JS方法创建DOM。

    【讨论】:

    • 我可以获取表格中的数据,但无法显示表格。提交表单后有什么方法可以显示表格吗?
    • 我将在答案中添加代码sn-p,演示如何在几分钟内将数据添加到表中
    • 我已经使用 cmets 添加了带有解释的代码
    • 此代码不起作用
    • 你遇到了什么错误?
    【解决方案3】:
    /* you can use below code */
    step 1: display date out of form 
    step 2: get data in $_POST
    
    if(isset($_POST)){
     /* retrieve data here  & display it */
    }
    

    【讨论】:

    • 最好提供一些带有答案的解释,而不仅仅是代码转储。这样,OP 就能更好地理解您的提议。
    【解决方案4】:

    <!DOCTYPE html>
    <html>
      <head lang="en">
      <meta charset="UTF-8">
      <script>
        function showData() {
            document.getElementById('displaydata').innerHTML = 
                        document.getElementById("txtInput").value;
        }
      </script>
    
      </head>
    <body>
    
      <form>
        <label><b>Enter Input</b></label>
        <input type="text" name="message" id="txtInput">
      </form>
    
      <input type="submit" onclick="showData();"><br/>
      <label>Your input: </label>
      <p><span id='displaydata'></span></p>
    </body>
    </html>
    enter code here
    

    【讨论】:

      【解决方案5】:

      要重新渲染页面,您可以使用 window.location.href = window.location.href。 但是由于您将表格显示为 none ,因此您还必须在那里进行条件检查。

      如果你正在使用 ajax,那么,

      $("form").submit(function (event) {
      event.preventDefault();
      var form = $(this)
      url = form.attr('action')
      var data = $("#my_date_picker").val()
      $.ajax({
        type: "POST",
        url: url,
        data: form.serialize(),
        beforeSend: function () {
        
        },
        success: function (data) {
          $('#datatable').append(`<tr>
              <td>data</td>
           </tr>`);
         $("#datatable").show();
         
        }
      })
      

      });

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-12
        • 2013-01-01
        • 1970-01-01
        • 2021-10-10
        • 1970-01-01
        • 2013-03-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多