dopuz8728 2016-01-29 16:16
浏览 55
已采纳

PHP / Javascript - 发布具有唯一ID的数据

I have an dynamic form with a add more button which creates an XML file that can be used for importing data.

The user fills out the form and can click more to add as many as they want. The data is then written to create a file via fwrite.

The problem is i'm using unique ID's and i need to get the values in order to create the file.

Here's the javascript https://jsfiddle.net/jdarville/mbfjmd02/6/

$(document).ready(function() {

    Number.prototype.pad = function(size) {
      var s = String(this);
      while (s.length < (size || 0)) {s = "0" + s;}
      return s;
    }

    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID

    var x = 1; //initlal text box count
    var c = 9;

    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            c++;
            $(wrapper).append('<div><label><span>Template Id :</span><input   type="text" name="templateid'+x+'" id="templateid'+x+'"></label><label><span>UNC Path :</span><input type="text" name="uncpath'+x+'" id="uncpath'+x+'"></label><label><span>Username :</span><input type="text" name="username'+x+'" id="username'+x+'"></label><label><span>Password :</span><input type="text" name="password'+x+'" id="password'+x+'"></label><label><span>Name :</span><input type="text" name="scantoname'+x+'" id="scantoname'+x+'"></label><a href="#" class="remove_field btn btn-primary">Remove</a></div>'); //add input box

            <!--add input value to "how many" field-->
            $.each($('input[name="howmany[]"]'), function() {
                $(this).val(x);
            });

            <!--add input value to "templateid" field-->
            $('input[name="templateid'+x+'"]').each(function() {
                $(this).val((x).pad(3,0));
            }); 
        }
    });

    $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

How do i post the data in PHP? I tried a bunch of stuff but its not working. :(

$templateid = @$_POST["templateid'+x+'"];
$uncpath = @$_POST["uncpath'+x+'"];
$username = @$_POST["username'+x+'"];
$password = @$_POST["password'+x+'"];
$scantoname = @$_POST["scantoname'+x+'"];


$f_data= '<?xml version="1.0" encoding="UTF-8"?>
<JobTemplates>
<GroupList>
<Group gid="000">
<MetaData>
<groupName>Public Template Group</groupName>
<userName />
<isPasswordProtected>false</isPasswordProtected>
<ownerName>Admin</ownerName>
<notificationEmail />
<TemplateCount>'.$templateid.'</TemplateCount>
<TemplateCount>'.$uncpath.'</TemplateCount>
<TemplateCount>'.$username.'</TemplateCount>
<TemplateCount>'.$password.'</TemplateCount>
<TemplateCount>'.$scantoname.'</TemplateCount>';

The end goal is to get a file that looks like this:

<JobTemplates>
<GroupList>
<Group gid="000">
<MetaData>
<groupName>Public Template Group</groupName>
<userName />
<isPasswordProtected>false</isPasswordProtected>
<ownerName>Admin</ownerName>
<notificationEmail />
<TemplateCount>001</TemplateCount>
<TemplateCount>\\test\test</TemplateCount>
<TemplateCount>bill</TemplateCount>
<TemplateCount>pass</TemplateCount>
<TemplateCount>bill crab</TemplateCount>
<JobTemplates>
<GroupList>
<Group gid="000">
<MetaData>
<groupName>Public Template Group</groupName>
<userName />
<isPasswordProtected>false</isPasswordProtected>
<ownerName>Admin</ownerName>
<notificationEmail />
<TemplateCount>002</TemplateCount>
<TemplateCount>\\test\test2</TemplateCount>
<TemplateCount>Mike</TemplateCount>
<TemplateCount>pass</TemplateCount>
<TemplateCount>Mike crab</TemplateCount>';
  • 写回答

3条回答 默认 最新

  • drk49438 2016-01-29 18:10
    关注

    Here'e a fully worked example, expanding upon what I mentioned earlier in my comments. Firstly, take note of the very different way I'm creating a new bunch of inputs when the user asks for them - I'm adding them all as elements, rather than as a text string. Secondly, I'm defining the fields I want in an array - this makes adding to or changing these fields very much quicker, easier and less error-prone.

    Next, you can see if you examine the generated html, that the inputs only have names, there's just no need to give them IDs in this case.

    Finally, you can see the PHP which simply echoes back the contents of the $_POST array.

    blank.html

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    "use strict";
    function byId(id){return document.getElementById(id);}
    function newEl(tag){return document.createElement(tag);}
    function newTxt(txt){return document.createTextNode(txt);}
    window.addEventListener('load', onDocLoaded, false);
    
    var nextIdToUseGlobal = 0;
    
    function onDocLoaded()
    {
        addFormElems( byId('fieldContainer'), nextIdToUseGlobal++ );
    }
    
    function addFormElems(fieldContainer, idToUse)
    {
        var formItems = [
                            {type: 'input', name: 'ids[]', label: 'Template Id:'},
                            {type: 'input', name: 'uncs[]', label: 'Unc Path:'},
                            {type: 'input', name: 'usernames[]', label: 'Username:'},
                            {type: 'input', name: 'passwords[]', label: 'Password:'},
                        ];
    
        formItems.forEach( formElemForEachFunc );
        fieldContainer.appendChild( newEl('hr') );
    
        function formElemForEachFunc(elem, index, list)
        {
            var curField = newEl( elem.type );
            curField.setAttribute('name', elem.name);
            if (index == 0)                             // 0 since this is the index of the id field in the above array
                curField.value = idToUse;
            fieldContainer.appendChild( newTxt(elem.label) );
            fieldContainer.appendChild( curField );
            fieldContainer.appendChild( newEl('br') );
        }
    }
    </script>
    <style>
    </style>
    </head>
    <body>
        <button onclick='addFormElems(byId("fieldContainer"),nextIdToUseGlobal++)'>Add new Scan Item</button><br>
        <form id='myForm' action='outputTest.php' method='post'>
            <div id='fieldContainer'></div>
            <input type='submit' value='Submit values'/>
        </form>
    </body>
    </html>
    

    outputTest.php

    <?php
        var_dump( $_POST );
    
        $numItems = count( $_POST["ids"] );     // get number of items in the ids array
        $ids = $_POST["ids"];
        $uncs = $_POST["uncs"];
        $users = $_POST["usernames"];
        $passwords = $_POST["passwords"];
    
        echo("<hr>");
        echo("You submitted $numItems items for scanning" . "<hr>");
    
        for ($i=0; $i<$numItems; $i++)
        {
            echo "ID: $ids[$i]" . "<br>";
            echo "UNC: $uncs[$i]" . "<br>";
            echo "username: $users[$i]" . "<br>";
            echo "password: $passwords[$i]" . "<br>";
            echo "<hr>";
        }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等