簡體   English   中英

將行添加到表並發送到服務器,通過jquery將表發布到php

[英]Add row to table and send to server, post table via jquery to php

我正在嘗試創建一個表,在其中可以單擊按鈕添加新行,然后將該表發送到服務器,以便它記住有關頁面刷新的信息。 下面是一個按鈕,該按鈕可將當前時間成功添加到表中。 但是,當我通過“發送到服務器”按鈕將表發送到服務器時,它不會回顯更新的表,而僅是原始​​表。 弄清楚這一點真是令人欣慰。

HTML:

<input type = "button" id = "send" value = "Send to Server" />
<input type = "button" id = "add" value = "Add Row" />
<table class="table table-striped">
        <tr>
            <td><h2>In</h2></td>
            <td><h2>Out</h2></td>
            <td><h2>Total</h2></td>
        </tr>
        <tr>
            <td>InData</td>
            <td>OutData</td>
            <td>TotalData</td>
        </tr>
</table>

JS:

<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">

$("#add").click(function(){

    var dt = new Date();
    var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); //set variable to current time
    $('table > tbody:last').append('<tr><td>'+time+'</td><td></td><td></td></tr>'); //add row to table with current time

});

$(function(){
    var dataArr = [];
    $("table").each(function(){
        dataArr.push($(this).html());
    });
    $('#send').click(function(){
        $.ajax({
          type : "POST",
          url : 'timesheet.php',
          data : "content="+dataArr,
          success: function(data) {
              alert(data);// alert the data from the server
          },
          error : function() {
          }
         });
    });
});
</script

PHP(timesheet.php):

<?php 
    echo $_REQUEST['content'];
?>

當我通過“發送到服務器”按鈕將表發送到服務器時,它不會回顯更新的表,而僅是原始​​表。

使用.on()而不是.on() .click()

<script language="javascript" type="text/javascript" src="jquery-1.8.2.js"></script>
<script language="javascript" type="text/javascript">

$(document).on('click', '#add', function(){

    var dt = new Date();
    var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds(); //set variable to current time
    $('table > tbody:last').append('<tr><td>'+time+'</td><td></td><td></td></tr>'); //add row to table with current time

});

$(document).on('click', '#send', function(){
    var dataArr = [];
    $("table").each(function(){
        dataArr.push($(this).html());
    });
    $('#send').click(function(){
        $.ajax({
          type : "POST",
          url : 'timesheet.php',
          data : "content="+dataArr,
          success: function(data) {
              alert(data);// alert the data from the server
          },
          error : function() {
          }
         });
    });
});
</script>

編輯:

您正在使用的click()綁定稱為“直接”綁定,它將僅將處理程序附加到已經存在的元素上。 它不會綁定到將來創建的元素。 為此,您必須使用on()創建一個“委托”綁定。

.on()文檔中

委派事件的優勢在於,它們可以處理來自后代元素的事件,這些事件在以后的時間添加到文檔中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM