简体   繁体   English

PHP数组变量中的Javascript变量?

[英]Javascript Variable in PHP Array Variable?

I'm working on an invoice system. 我正在开发发票系统。 By default it loads with 1 row to input items. 默认情况下,它加载1行以输入项目。 If a administrator wants to add additional items they may click a link which executes a JavaScript to add additional rows. 如果管理员想添加其他项目,他们可以单击执行JavaScript的链接来添加其他行。 This is working great for me. 这对我来说很棒。

I submit the form using POST method to the same page. 我使用POST方法将表单提交到同一页面。 If a user added additional rows using the JavaScript, it loads with the previous amount of rows as when the page was submitted. 如果用户使用JavaScript添加了其他行,则它将与提交页面时一样加载以前的行数。 To do this I used PHP $table_rowcount = count( $_POST["item_details"] ); 为此,我使用了PHP $table_rowcount = count( $_POST["item_details"] ); . Just FYI, the {$table_rowcount} isn't a syntax error as I'm using a template engine. 仅供参考, {$table_rowcount}不是语法错误,因为我使用的是模板引擎。

Everything works great to this point. 到目前为止,一切都很好。 Administrators can add additional rows to input data and when the page is submitted to itself it loads those number of rows. 管理员可以在输入数据中添加其他行,并且当页面提交给自己时,它会加载这些行数。 Perfect. 完善。 However this is where the problem comes in. 但是,这就是问题所在。

What I need to do is use a method of sticky forms so if there is an error, the page will reload (as it currently does) with variables assigned to each inputs value="" so the administrator wont have to re-enter all the details. 我需要做的是使用粘性表格的方法,因此,如果出现错误,页面将重新加载(如当前那样),并为每个输入value=""从而使管理员不必重新输入所有细节。

The problem is I do not know how to do this with a combination of JavaScript and PHP. 问题是我不知道如何结合使用JavaScript和PHP。 I need to some how get the current number of the row using the for() loop in JavaScript and then use that number in a PHP variable as seen in the tbody of the HTML below for the default 1st row. 我需要一些如何使用JavaScript中的for()循环获取当前行号,然后在PHP变量中使用该行号的方法,如下面的HTML正文中的默认第一行所示。

Basically if it is the 3rd row and the for() loop will show it as var i = 2 (since array starts at 0), how can I use JavaScript to help me call the PHP variable {$item.2.details} . 基本上,如果它是第三行,并且for()循环将其显示为var i = 2 (因为数组从0开始),那么如何使用JavaScript来帮助我调用PHP变量{$item.2.details}

I'm assuming I need to use AJAX for this? 我假设我需要为此使用AJAX? However I do not know AJAX. 但是我不知道AJAX。 I'm hoping someone could assist me with this so myself and others can learn how this is properly done. 我希望有人可以协助我完成这项工作,以便我自己和其他人可以学习如何正确地做到这一点。

Question simply put 问题简单地说

How can I use a JavaScript variable to select a PHP array in a HTML file? 如何使用JavaScript变量在HTML文件中选择PHP数组?

JavaScript: JavaScript:

<script type="text/javascript">
window.onload = function loadRows() {
    for( i = 1; i < {$table_rowcount}; i++ ) {

        // Set table id.
        var table = document.getElementById("invoice_items");

        // Count rows.
        var rowCount = table.rows.length;

        // Row to insert into table.
        var row = table.insertRow(rowCount);

        // Cells to insert into row.
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        var cell3 = row.insertCell(2);

        // Current Row.
        var rowNumber = rowCount + 1;

        // Data in cells.
        cell1.innerHTML = "<textarea name=\"item_details[]\"></textarea>";
        cell2.innerHTML = "<input type=\"text\" name=\"item_quantity[]\" value=\"\" />";
        cell3.innerHTML = "<input type=\"text\" name=\"item_price[]\" value=\"\" />";
    }
}
</script>

HTML: HTML:

<form method="post" action="index.php?do=invoices_add">

    <label class="label">
        <div class="left">
            Invoice Items
        </div>
        <table id="invoice_items" cellpadding="0" cellspacing="0" border="0">
            <thead>
                <tr>
                    <td>
                        Item Details
                    </td>
                    <td>
                        Quantity
                    </td>
                    <td>
                        Price
                    </td>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <textarea name="item_details[]">{$item.0.details}</textarea>
                    </td>
                    <td>
                        <input type="text" name="item_quantity[]" value="{$item.0.quantity}" />
                    </td>
                    <td>
                        <input type="text" name="item_price[]" value="{$item.0.price}" />
                    </td>
                </tr>
            </tbody>
        </table>
        <a href="#invoice_items" onclick="addRows()">+ Add Item</a>
    </label>
    <br/>

    <label class="label">
        <input type="submit" value="submit" name="submit" />
    </label>

</form>

Just to make sure I understand correctly: You have users who enter new rows, and if there is an error, their newly entered rows are lost, along with the information they typed. 只是为了确保我理解正确:您有输入新行的用户,如果出现错误,他们新输入的行以及他们输入的信息将丢失。 Based on that: 基于此:

My first instinct is to post the form via AJAX, but if you want to go the PHP route, I would recommend researching session based flash messages . 我的第一个直觉是通过AJAX发布表单,但是如果您想走PHP路线,建议您研究基于会话的Flash消息 You can use session data to send back the values which have already been input, along with additional error messages. 您可以使用会话数据发送回已输入的值以及其他错误消息。 I have previously set flash data as one object with property names such as "errors". 我之前已将Flash数据设置为具有“错误”之类的属性名称的对象。 "errors" would be an array of error messages, but you can also set a property called "additionalItem" and add the newly created items by the user. “错误”将是错误消息的数组,但是您也可以设置一个名为“ additionalItem”的属性,并由用户添加新创建的项目。 Then add these to your row iteration in the PHP, avoiding the necessity of using JavaScript to build the rows. 然后将它们添加到PHP的行迭代中,避免使用JavaScript来构建行的必要。

$flashData = Array("additionalItem" => Array());

for ($_PARAMS["addedRows"] as $row) {
    $flashData["additionalItem"] []= Array(
        "rowDetails" => $row['details'],
        "rowQuantity" => $row['quantity'],
        "rowPrice" => $row['price']
    )
}

I would also recommend client side validation where possible. 我还建议尽可能进行客户端验证。 However, I also understand other non-client-side errors can arise. 但是,我也理解可能会出现其他非客户端错误。

If you have to do it in JavaScript then I think your best option here is to expose the PHP array you want to iterate over and store it as a JavaScript variable (so either way you will probably need to set flash data). 如果您必须使用JavaScript进行操作,那么我认为最好的选择是公开要迭代的PHP数组,并将其存储为JavaScript变量(因此,您可能都需要设置闪存数据)。

<script type="text/javascript">
  // I renamed item to items as I am assuming you have an array.
  // This would preferably be an array of items from the server.
  var items = {$items},
      table = document.getElementById("invoice_items");

  window.onload = function loadRows() {
    for (i = 1; i < items.length; i++) {
      var rowCount = table.rows.length,
          row = table.insertRow(rowCount),
          cell1 = row.insertCell(0),
          cell2 = row.insertCell(1),
          cell3 = row.insertCell(2),              
          rowNumber = rowCount + 1;

      cell1.innerHTML = "<textarea name='item_details[]'>" + 
          items[i].details + "</textarea>";
      cell2.innerHTML = "<input type='text' name='item_quantity[]' 
          value='' />";
      cell3.innerHTML = "<input type='text' name='item_price[]' 
          value='' />";
    }
  }
</script>

I hope this helps and that I did not misunderstand the question :) 我希望这会有所帮助,并且我不会误会这个问题:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM