0
$(document).ready(function() {
    var id = 1;

    $("#butsend").click(function() {
        $("#table1").append('<tr valign="top">\n\
            <td width="100px">' + (id++) + '</td>\n\
            <td width="100px">' + $("#sname").val() + '</td>\n\
            <td width="100px">' + $("#age").val() + '</td>\n\
            <td width="100px"><a href="javascript:void(0);" class="remCF">Remove</a></td>\n\
        </tr>');
    });

    var serializedData = $('#form1').serialize();

    $.ajax({
        url: "save.php",
        type: "post",
        data: serializedData
    });

    $("#table1").on('click', '.remCF', function() {
        $(this).parent().parent().remove();
    });
});
<form id="form1" name="form1" method="post">
    <label>Student Name</label><input type="text" name="sname" id="sname"></br>
    <label>Student Age</label><input type="text" name="age" id="age"></br>
    <input type="button" name="send" value="send" id="butsend"></br>
    <input type="button" name="save" value="Save" id="butsave"></br>
</form>

<table id="table1" name="table1" border="0">
    <tbody>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Age</th>
            <th></th>
        <tr>
        <tr>
            <td></td>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </tbody>
</table>

我正在使用 jQuery 将多个表单数据添加到表中。然后我想在单击保存按钮时将添加的数据发送到数据库表。我的示例代码在这里。你能帮帮我吗?谢谢 http://jsfiddle.net/eruZC/3/

4

3 回答 3

0

需要将插入的值作为 json 类型返回给模型。

<style type="text/css">
    #table1 tr {
        vertical-align: top;
    }

        #table1 tr td {
            width: 100px;
        }
</style>
<script type="text/javascript">
    $(document).ready(function () {
        $("#butsend").click(function () {
            if (true) {//Check Validation
                $.ajax({
                    url: "save.php", type: "post",
                    data: $.param($('#form1').serializeArray()),
                    //data: JSON.stringify({}),//Pass json model
                    success: function (data) {
                        $("#table1").append('<tr><td>' + data.model.id + '</td><td>' + data.model.sname + '</td><td >' + data.model.age
                            + '</td><td><a class="remCF" data-id="' + data.model.id + '">Remove</a></td></tr>');
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        console.log(textStatus, errorThrown);
                    },
                    complete: function (msg) {
                    }
                });
            }
        });

        $("#table1").on('click', '.remCF', function () {
            var $this = $(this).parents('tr');
            $.ajax({
                url: "remove.php", type: "post", dataTye: "json",
                data: { id: $(this).data('id') },
                success: function (data) {
                    $this.remove();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                },
                complete: function (msg) {

                }
            });
        });
    });
</script>

这是 ASP.net mvc 3 调用控制器操作方法的以下示例

我不知道如何返回 json 结果我 php

$.ajax({
     url: "/controllername/actionmethodname"
});

[HttpPost]
public JsonResult Add(News vm)
{
    using (var db = new Mvc3MDbContext())
    {
       //vm used contains id, name, etc
    }

    return Json(new { model = vm }, JsonRequestBehavior.AllowGet);
}
于 2013-09-12T15:23:41.183 回答
0

当您单击添加按钮时,您还可以调用 php 连接到您的数据库,然后插入表单数据。做一些类似于下面的 php 应该允许你插入到你的数据库中并且仍然显示在你的表中。快速 google 可以提供有关使用 php 连接到数据库并与之交互的其他信息。

$("#butsend").click(function() {
    $("#table1").append('<tr valign="top">\n\
        <td width="100px">' + (id++) + '</td>\n\
        <td width="100px">' + $("#sname").val() + '</td>\n\
        <td width="100px">' + $("#age").val() + '</td>\n\
        <td width="100px"><a href="javascript:void(0);" class="remCF">Remove</a></td>\n\
    </tr>');

    <?php
        #connect to DB
        $con=mysqli_connect("hostname","username","password","database_name");
        #Check connection
        if (mysqli_connect_errno())
        {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }      
        #what you want to insert into the database
        $query = "INSERT INTO table_name (table_field_id,table_field_name,table_field_age) VALUES ($id, name, age)";
        #insert into database
        mysqli_query($con,$query);
        #close database connection
        mysqli_close($con);
    ?>
});
于 2013-09-12T17:58:23.943 回答
0

遵循这些可能会失败的步骤。

  • 使用脚本为trtd标签动态分配唯一 ID以进行分隔
  • 使用唯一 id,只需获取 tr 和 td 标签的值。
  • 将值保存在json对象中并将其发布到PHP
  • 使用 PHP,将从脚本接收到的值保存到Mysql数据库。

按照上述步骤,将其添加到您的脚本标签

    $(document).ready(function() {
    var id = 1;  
    //Assigning id and class for tr and td tags for separation.

    $("#butsend").click(function() {
        var newid = id++; 
        $("#table1").append('<tr valign="top" id="'+newid+'">\n\
            <td width="100px" >' + newid + '</td>\n\
            <td width="100px" class="name'+newid+'">' + $("#sname").val() + '</td>\n\
            <td width="100px" class="age'+newid+'">' + $("#age").val() + '</td>\n\
            <td width="100px"><a href="javascript:void(0);" class="remCF">Remove</a></td>\n\
        </tr>');

    });

    var serializedData = $('#form1').serialize();

    $.ajax({
        url: "save.php",
        type: "post",
        data: serializedData
    });

    $("#table1").on('click', '.remCF', function() {
        $(this).parent().parent().remove();
    });

   // crating new click event for save button

    $("#butsave").click(function() {
        var lastRowId = $('#table1 tr:last').attr("id"); //finds id of the last row inside table


        var name = new Array();  
        var age = new Array();   
        for ( var i = 1; i <= lastRowId; i++) {
            name.push($("#"+i+" .name"+i).html());  //pushing all the names listed in the table
            age.push($("#"+i+" .age"+i).html());   //pushing all the ages listed in the table
        }
        var sendName = JSON.stringify(name);  
        var sendAge = JSON.stringify(age);
        $.ajax({
            url: "save.php",
            type: "post",
            data: {name : sendName , age : sendAge},
            success : function(data){
                alert(data);    // alerts the response from php.
                }
        });
        });
});

将此添加到 PHP( save.php )

    <?php
$nameArr = json_decode($_POST["name"]);
$ageArr = json_decode($_POST["age"]);
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

for ($i = 0; $i < count($nameArr); $i++) {

    if(($nameArr[$i] != "")){       //not allowing empty values and the row which has been removed.
    $sql="INSERT INTO table_name (Name, Age)
VALUES
('$nameArr[$i]','$ageArr[$i]')";
    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    }

}

Print  "All records added";

mysqli_close($con);
?>
于 2013-09-13T06:25:54.950 回答