简体   繁体   English

使用Jquery和Ajax更新HTML表

[英]Updating HTML table using Jquery & ajax

I want to update table data without refreshing the page using Ajax and Jquery. 我想更新表数据而不使用Ajax和Jquery刷新页面。

I know I will need setInterval() method, because I want the table to be refreshed to all users, because multiple users could insert data in to the database and I want to update the table to every user. 我知道我将需要setInterval()方法,因为我希望将表刷新给所有用户,因为多个用户可以在数据库中插入数据,并且我想向每个用户更新表。

I have made a script to send the data from a form without redirecting the user or refreshing the page and then insert it in the database. 我已经制作了一个脚本来从表单发送数据,而无需重定向用户或刷新页面,然后将其插入数据库。

MyScript.js MyScript.js

$( document ).ready(function() {
    console.log( "Ready!" );
    //Submitting from data
    $("#submitForm").submit(function(e){
        if($('#fName').val() && $('#lName').val() && $('#nickname').val()) {
            $.ajax({
               type: "POST",
               url: "process.php",
               data: $("#submitForm").serialize(),
               success: function(data){
                   console.log(data); // show response from the php script.
               }
             });
         }
         else {
             alert("Please fill the fields.")
         }
        e.preventDefault();
    });
}); 

In my process.php file I insert the data to the database. 在我的process.php文件中,将数据插入数据库。

Now I have info.php file that generates my table with all the data and I have a form there to insert new data. 现在,我有了info.php文件,该文件将使用所有数据生成表,并且在那里有一个表单可以插入新数据。

<div id="table" class="col-md-7 ml-5">
  <table class="table table-striped table-bordered table-hover table-sm">
    <thead class="thead-default">
      <tr>
        <th>#</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Nickname</th>
        <th>User ID</th>
      </tr>
    </thead>
    <?php $user->showUsers(); ?>
  </table>
</div>

the showUsers() function just generate the other rows of the table with the data from SQL. showUsers()函数仅使用来自SQL的数据生成表的其他行。

I have no idea how to refresh the table using Jquery and Ajax. 我不知道如何使用Jquery和Ajax刷新表。
I tried to use the .load() method, but it also generates the html for my form. 我尝试使用.load()方法,但它也会为我的表单生成html。

Please help. 请帮忙。

As you said, you can use setInterval or better setTimeout since you want the return of the data to trigger a new request later 如您所说,您可以使用setInterval或更好的setTimeout,因为您希望稍后返回数据以触发新请求

var tId="";
function getInfo() {
  $.get("info.php #table",function(data) {
    tId = setTimeout(getInfo,60000);
    $("#someContainer").append(data);
  });
}
getInfo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM