Best way to submit UL via POST?

后端 未结 4 1174
春和景丽
春和景丽 2020-12-18 04:38

Quick question...

I have an input box that upon key enter, adds the value to an unordered list. How would I pass this unordered list to jquery post? I\'m using the f

相关标签:
4条回答
  • 2020-12-18 05:14

    when you add thing dynamically to your UL you can add hidden inputs with array name like

    <input type='hidden' name='ul[1]' value='banana'/>
    <input type='hidden' name='ul[2]' value='apple'/>
    <input type='hidden' name='ul[3]' value='pear'/>
    
    0 讨论(0)
  • 2020-12-18 05:16
    <ul>
        <li>Apple<input type='hidden' name='fruits[]' value='Apple'/></li>
        <li>Pear<input type='hidden' name='fruits[]' value='Pear'/></li>
        <li>Banana<input type='hidden' name='fruits[]' value='Banana'/></li>
    </ul>
    

    When submitted, you'll get an array in $_POST named fruits with those value.

    0 讨论(0)
  • 2020-12-18 05:27

    Something like that (dynamic construction of the ul content):

    <html>
    <head>
        <title>S.O. 3287336</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function() {
            $('#add').click(function() {
                var li = $('<li></li>').text($('#edit').val());
                $('#ul').append(li);
            });
    
            $('#addForm').submit(function() {
                var ul = "";
    
                $('#ul li').each(function() {
                    ul += $(this).html() + ";"
                });
    
                alert("About to submit: " + ul); 
                return false; // don't submit
            });
        });
        </script>
    </head>
    <body>
    <ul id="ul">
    </ul>
    <form id="addForm">
        <input type="text" name="edit" id="edit" value=""/>
        <input type="button" id="add" value="Add"/>
        <input type="submit" id="submit-btn" value="End"/>
    </form>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-18 05:28

    Something similar works with Pythons Flask, but you have to use request.form.getlist(arg) instead of just "get".

    In fruits.html:

    <form action='/test' method="post">
        <ul>
            <li>Apple<input type='hidden' name='fruits' value='Apple'/></li>
            <li>Pear<input type='hidden' name='fruits' value='Pear'/></li>
            <li>Banana<input type='hidden' name='fruits' value='Banana'/></li>
        </ul>
        <input type="submit">
    </form>
    

    In app.py:

    @app.route('/fruits', methods=['GET', 'POST'])
    def get_fruits():
    if request.method == 'POST':
        fruits = request.form.getlist("fruits")
        print fruits
    return render_template(fruits.html)
    

    This will print out:

    ['Apple', 'Pear', 'Banana']
    
    0 讨论(0)
提交回复
热议问题