1

所以这是我的情况。我有一个表单,它使用户能够向表单添加任意数量的行并将更多数据输入到那些新创建的行中(使用 javascript)。我已经在下面的代码中设置了这个(我正在使用 index.html、js/scripts.js 和 php/upload.php 文件,所有文件都是外部链接的,包括外部 CSS):

索引.HTML

<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
 <script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">   
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
 <title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>

<input type="hidden" id="co_city">
<input type="hidden" id="co_state">
<input type="hidden" id="co_zipcode">

<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
    <td><select id="company_name"></select></td>
    <td><input id="co_name" type="text"></td>
    <td><input type="submit" value="Get GPS" onclick="gpslookup()"></td>
    <td><input id="co_lat" type="text"></td>
    <td><input id="co_long" type="text"></td>
    <td><input id="co_address" type="text"></td>
</tr>
</table>
<table id="tabledata">
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
<!--Begin Rows-->
<tr>
    <td><input type="checkbox"></td>
    <td><input id="border_location" type="text" name="txt[]"></td>
    <td><input id="cable_location" type="text" name="txt[]"></td>
    <td><input id="vault_direction" type="text" name="txt[]"></td>
    <td><input id="cable_type" type="text" name="txt[]"></td>
    <td><input id="cable_size" type="text" name="txt[]"></td>
    <td><input id="cable_gauge" type="text" name="txt[]"></td>
    <td><input id="vertical" type="text" name="txt[]"></td>
    <td><input id="jumpers" type="text" name="txt[]"></td>
    <td><input id="protectors" type="text" name="txt[]"></td>
    <td><input id="metered_dist" type="text" name="txt[]"></td>
    <td><input id="comments" type="text" name="txt[]"></td>
</tr>
</table>
<input id="addrow_btn" type="submit" value="Add New Row" onclick="addRow(); return false;" />
<input id="delrow_btn" type="submit" value="Delete Row" onclick="deleteRow(); return false;" />
<input id="submit" type="submit" value="Submit" onclick="uploaddata(); return false;"  />
</body>
</html>

至于后端,我只有 PHP 和服务器端脚本能够使用以下代码提交第一行的信息:

JAVASCRIPT 文件

function addRow() {

var table = document.getElementById("tabledata");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);

var colCount = table.rows[1].cells.length;

for(var i=0; i<colCount; i++) {

    var newcell = row.insertCell(i);

    newcell.innerHTML = table.rows[1].cells[i].innerHTML;
    //alert(newcell.childNodes);
    switch(newcell.childNodes[0].type) {
        case "text":
                newcell.childNodes[0].value = "";
                break;
        case "checkbox":
                newcell.childNodes[0].checked = false;
                break;
    }
}
//UPLOAD DATA
//Global variables
var survey = {
    'co_name' : "",
    'co_lat' : "",
    'co_long' : "",
    'co_address' : "",
    'border_location' : "",
    'cable_location' : "",
    'vault_direction' : "",
    'cable_type' : "",
    'cable_size' : "",
    'cable_gauge' : "",
    'vertical' : "",
    'jumpers' : "",
    'protectors' : "",
    'metered_dist' : "",
    'comments' : "",
    'company_name' : "",
    'co_city' : "",
    'co_state' : "",
    'co_zipcode' : ""
    }

function uploaddata() { 

//Read all of the data from the page
for (eID in survey) {
    survey[eID] = document.getElementById(eID).value;
}   
 //Insert data into database

            $.ajax({
            type: 'POST',
            url: './php/upload_survey.php',
            data: survey,
            async: false,
            dataType: 'text',
            success: function() {
            alert("Thank you. Your survey has been submitted.");
            window.location.reload();
            },

                error: function(jqXHR, textStatus, errorThrown) {
                    alert("Error... " + textStatus + "\n" + errorThrown);
                }
        });
    }

PHP文件

//Assign passed parameters

    $co_name = $_POST['co_name'];
    $co_lat = $_POST['co_lat'];
    $co_long = $_POST['co_long'];
    $co_address = $_POST['co_address'];     
    $border_location = $_POST['border_location'];
    $cable_location = $_POST['cable_location'];
    $vault_direction = $_POST['vault_direction'];
    $cable_type = $_POST['cable_type'];
    $cable_size = $_POST['cable_size'];
    $cable_gauge = $_POST['cable_gauge'];
    $vertical = $_POST['vertical'];
    $jumpers = $_POST['jumpers'];
    $protectors = $_POST['protectors'];
    $metered_dist = $_POST['metered_dist'];
    $comments = $_POST['comments'];
    $txt = $_POST['txt'];

    $stringLogInfo =  "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
    log_audit($logAuditFile, $logModule, $stringLogInfo);

//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);



//Insert Survey Form Information into the database
    $fieldlist=$vallist='';
    foreach ($_POST as $key => $value) {
        $fieldlist.=$key.',';
        $vallist.='\''.$value.'\','; 
    }
    $fieldlist=substr($fieldlist, 0, -1);
    $vallist=substr($vallist, 0, -1);
    $sql='INSERT INTO table_name ('.$fieldlist.') VALUES ('.$vallist.')';

mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());

到目前为止,我的目标是,已经准备好其他一切,能够根据他们创建的行数来遍历表单中的所有数据,并将所有这些新行值提交到 SQL 数据库中的单独行中. 请指教!

4

1 回答 1

0

这里关注这个问题的 HTML 部分是一种动态增长表单的方法:

首先是 HTML:

<table id="tabledata">
    <thead>
        <th>Select</th>
        <th>Border Location Name</th>
        <th>Cable Location</th>
        <th>Direction of Vault Wall</th>
        <th>Cable Type</th>
        <th>Cable Size (pairs)</th>
        <th>Cable Gauge</th>
        <th>Vertical(s) appeared on Verticals</th>
        <th>Approximate Number of Jumpers</th>
        <th>Are Protectors Still In?</th>
        <th>Metered Distance</th>
        <th class="comments">Central Office Comments</th>
    </thead>
    <tbody id="input"></tbody>
    <tbody id="template">
        <tr>
            <td><input name="selected" type="checkbox" /></td>
            <td><input name="border_location" type="text" /></td>
            <td><input name="cable_location" type="text" /></td>
            <td><input name="vault_direction" type="text" /></td>
            <td><input name="cable_type" type="text" /></td>
            <td><input name="cable_size" type="text" /></td>
            <td><input name="cable_gauge" type="text" /></td>
            <td><input name="vertical" type="text" /></td>
            <td><input name="jumpers" type="text" /></td>
            <td><input name="protectors" type="text" /></td>
            <td><input name="metered_dist" type="text" /></td>
            <td><input name="comments" type="text" /></td>
        </tr>
    </tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button id="ActionSubmit">Submit</button>

这个JavaScript:

$(function () {
    var addInputRow = function () {
        $('#input').append($('#template').html());
    };

    addInputRow();
    $('#ActionAddRow').on('click', addInputRow);
    $('#ActionSubmit').on('click', function () {
        var data = $('#input tr').map(function () {
            var values = {};
            $('input', $(this)).each(function () {
                if (this.type === 'checkbox') {
                    values[this.name] = this.checked;
                } else {
                    values[this.name] = this.value;
                }
            });
            return values;
        }).get();
        $.post('/echo/json/', {
            json: JSON.stringify(data),
            delay: 1
        }).done(function (response) {
            alert("POST success");
            console.log(response);
        });
    });
});

然后这个CSS:

tbody#template {
    display: none;
}

制作这个演示

这是正在发生的事情的细分。首先,该table元素可以定义多个主体,因此我添加了空输入行的 HTML,并将其隐藏(使用 CSS)在atbodyIDtemplate然后,我使用 JavaScript 定义了一个简单的函数,该函数只是将该行的内容附加到tbodyID 为 的 ,inputs并将该函数绑定到clicka 的事件button。然后因为输入tbody一开始是空的,所以我调用了一次该函数。然后为了提​​交表单,我选择所有行inputs tbody并遍历inputs在他们里面找到。接下来,我将它们组合成一个大型 JavaScript 对象数组,每个元素代表一行,最后我发布这个显示从客户端到服务器的数据往返(我正在使用 JSON2.js 序列化数据)。您的 PHP 页面将从此处获取以在服务器上检查它们,并(使用准备好的语句)将有效行插入数据库。

您的 PHP 将采用这样的 POSTed 值:

$value = json_decode($_POST['json']);

并将提交的数据视为关联数组。此方法使用 AJAX 表单发布,因此 PHP 页面的响应应该是有效的 JSON,其结构如下:

{Success: true}
于 2013-03-06T19:25:40.257 回答