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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)