【问题标题】:Can Jquery update/insert new table rows when new database entry?新数据库条目时,Jquery 可以更新/插入新表行吗?
【发布时间】:2011-06-07 01:59:16
【问题描述】:

我有一个使用 PHP/mysql 填充的基本 html 表。当使用 jQuery 将新行插入我的数据库时,谁能建议我如何在表格顶部更新或插入新表格行?

我用 Google 搜索过,但只能找到如何更新 div,例如:

$(document).ready(function(){

var auto_refresh = setInterval(
function ()
{
$('#some_div').load('test.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds

});

如果有人能帮我解决这个问题,我将不胜感激。

【问题讨论】:

    标签: php jquery mysql html-table polling


    【解决方案1】:

    Javascript无法接收来自数据库的推送通知,所以你给出的例子是正确的。

    但是,您可以通过 AJAX 向 Javascript 返回一些值来轮询服务器是否有更改,该值告诉您数据是否已更改,然后触发刷新显示这些结果的页面部分的 AJAX 请求。

    无论哪种方式,您都必须使用setInterval() 调用来轮询服务器以进行更改。有一些方法可以启用 HTTP 流,但这有点超出了这个问题的范围。

    编辑:为简洁起见,我将用 jQuery 编写一个示例:

    var getCurrentDate = function() {
      return (new Date()).toUTCString();
    };
    
    var lastPing = getCurrentDate();
    
    setInterval(function() {
      $.post(
        '/service/getNewData',
        { from: lastPing },
    
        function(data) {
          // set the timestamp for the next request
          lastPing = getCurrentDate();
    
          // assuming the server returns a JSON array of rows
          $('body').append('<p>Last inserted ID: ' + data[data.length - 1].ID + '</p>');
    
          // you could run a for loop here for each row in data
          for(var i = 0; i < data.length; i++) {
            // ....
          }
    
        }
      );
    }, 5000);
    

    此代码请求/service/getNewData URL,并发送上次发送请求的UTC字符串;这使服务能够找到时间戳大于 AJAX 调用发送的 UTC 时间戳的行。您只需将行作为带有正确 HTTP 标头的正确 JSON 字符串发回即可。

    json_encode()

    【讨论】:

    • 我想要一个你上面描述的例子,我在想类似的东西,但我不擅长 javascript。
    • 另外,您可能希望接受此处给出的答案之一。
    【解决方案2】:
    function update() {
        $.ajax({
            type: 'GET',
            url: 'some.php',
            data: $('form#my_form').serialize(),
            success: function(data) {
                $("#some").html(data);
                window.setTimeout(update, 10000);
            }
        });
    };
    
    $(document).ready(function() {
    update();
    });
    
    
    <?php
    //some.php
    echo '<pre>';
    //just for  visualization
    print_r($_GET);
    echo '</pre>';
    
    //here do insert update database
    //after db insert update return some data as json (object)
    echo json_encode($return, JSON_FOCE_OBJECT);
    // echo json_encode($return); //if php<5.3
    ?>
    

    【讨论】:

      【解决方案3】:

      不确定 jQuery,但您可以使用 AJAX 和一些简单的 PHP 代码行。

      您可以将此代码用于 ajax 请求:

      function updateTable() {
      if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
        }
      else
        {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
      xmlhttp.onreadystatechange=function()
        {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
          {
                     //**Place the js table append code**
          }
        }
      xmlhttp.open("GET","getSQLrows.php",true);
      xmlhttp.send();
      }
      

      getSQLrows.php:

      <?php
      
      $query = mysql_query("SELECT * FROM table WHERE used = 0");
      while ($result = mysql_fetch_array($query)) {
          echo $result['field'];
          mysql_query("UPDATE table SET used = 1 WHERE id = $result['id']");
      }
      
      ?>
      

      这只是一个非常普遍的示例,说明如何根据您的需求实施这种解决方案。

      【讨论】:

        【解决方案4】:

        你可以用你的输入字符串改变你网站上的元素..

        HTML:

        <div id='test'></div>
        

        查询:

        // Instant method to feedback user..
        $('#test').text('your_new_data'); // if $.ajax is success do it
        

        它可以用新数据替换你以前的数据..

        如果你想知道text method

        【讨论】:

          【解决方案5】:

          我建议使用模型中的 clone() 将行添加到您的 html 中,如下所示:

          <style type="text/css">
            #line_model {
              display: none;
            }
          </style>
          
          <script type="text/javascript">
          $(document).ready(function () {
            $('#add_line').click(function () {
              $('#line_model').clone().prependTo('#editor_lines').show();
            });
          });
          </script>
          
          <div id="editor">
            <input type="button" id="add_line" value="add_line" />
            <div id="line_model">
              <input name="field1[]" />
              <input name="field2[]" />
            </div>
            <div id="editor_lines">
              <div class="line">
                <input name="field1[]" value="test1" />
                <input name="field2[]" value="test2" />
              </div>
              <div class="line">
                <input name="field1[]" value="test3" />
                <input name="field2[]" value="test4" />
              </div>
            </div>
          </div>
          

          这将允许您只定义一次线路的行为。

          要更新您的数据库,您可以使用update() function by predrag.music

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多