使用Jquery&更新HTML表。阿贾克斯

时间:2017-03-11 20:00:48

标签: javascript php jquery mysql ajax

我想更新表数据而不使用Ajax和Jquery刷新页面。

我知道我需要setInterval()方法,因为我希望将表刷新给所有用户,因为多个用户可以将数据插入到数据库中,我想将表更新为每个用户。

我制作了一个脚本,可以从表单发送数据,而无需重定向用户或刷新页面,然后将其插入数据库。

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();
    });
}); 

在我的process.php文件中,我将数据插入数据库。

现在我有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>

showUsers()函数只使用SQL中的数据生成表的其他行。

我不知道如何使用Jquery和Ajax刷新表。
我尝试使用.load()方法,但它也为我的表单生成了html。

请帮忙。

1 个答案:

答案 0 :(得分:0)

正如你所说,你可以使用setInterval或更好的setTimeout,因为你想要返回数据以便稍后触发新请求

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