Sending HTML Form Multiple <select> box via

2019-07-22 01:08发布

I have an html form with a multiple select box. I can't figure out how to send the values to my php application with AJAX via a post request. It works just fine if I use a GET request and use a single select box but not when I use a multiple select box. The idea is for users to hold control (or command with mac) and select one or more categories. Depending on which categories are selected will determine what other form options will be displayed using AJAX. The select box looks like this:

Edit: SOLVED

<select multiple name="categories[]" onclick="sendCategories(this)">
<option value="0">Category 1</option>
<option value="1">Category 2</option>
<option value="2">Category 3</option>
</select>

My javascript function looks like this:

function sendCategories(sel){
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("my_div").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var values = $(sel).serialize();
    xmlhttp.send(values);
}

4条回答
孤傲高冷的网名
2楼-- · 2019-07-22 01:32

You'll have to generate the query string to send in the POST on your own. Here's the HTML tag to use:

<select multiple name="categories[]" onchange="sendCategories(this);">

And the Javascript function:

function sendCategories(sel){
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
            document.getElementById("my_div").innerHTML = xmlhttp.responseText;
        }
    };
    xmlhttp.open("POST","http://www.mysite.com/update_categories.php",true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    var values = [], i, j, cur;
    for (i = 0, j = sel.options.length; i < j; i++) {
        cur = sel.options[i];
        if (cur.selected) {
            values.push(encodeURIComponent(cur.value));
        }
    }
    if (values.length) {
        values = encodeURIComponent(sel.name) + "=" + values.join("&" + encodeURIComponent(sel.name) + "=");
    } else {
        values = null;
    }

    xmlhttp.send(values);
}

Note that I changed the event from onclick to onchange, but that's really up to you whether you want this function to run when the element is clicked, or its value is truly changed...it can reduce some unnecessary calls.

This should generate a querystring that is normally used for sending values for a <select> with multiple options selected.

Here's a jsFiddle that demonstrates how the querystring is being generated here: http://jsfiddle.net/kKWQM/

查看更多
forever°为你锁心
3楼-- · 2019-07-22 01:48

You can implement the solution however you would like using JS string and array functions. Effectively, the string you need to send to Apache should contain a pattern like:

xxx[]=a&xxx[]=b&xxx[]=c

where the SELECT element's name is xxx[] in your form and a, b, and c are three values the user selected.

So yes, you are repeating a key name as many times as the user selected a different option in the SELECT.

In JS you can use an array of selected options:

selected_options.join("&xxx[]=") to produce that pattern.
查看更多
劳资没心,怎么记你
4楼-- · 2019-07-22 01:49

jQuery should make this easier for you. Calling .val() on a wrapped select returns an array of the selected values. You just have to post these to the server:

HTML:

<html>
    <body>
        <form>
            <select name="mySelect" multiple="on">
                <option value="1">Uno</option>
                <option value="2">Dos</option>
                <option value="3">Tres</option>
            </select>
        </form>
        <input id="submitButton" type="button" value="Click To Submit"/>
    </body>
</html>

JavaScript:

$(function() {
    $('#submitButton').click(function() {
        var valuesArray = $('select[name=mySelect]').val()
        $.ajax({
            type: 'POST',
            url: '/path/to/php', // your php url would go here
            data: { mySelect: valuesArray }
        }).done(function(msg) {
            // parse response from msg
        });
    });
});
查看更多
ゆ 、 Hurt°
5楼-- · 2019-07-22 01:53

You can do something like this,

<select multiple name="categories[]" onclick="sendCategories(this)">

And Make AJAX using JQuery,

function sendCategories(sel){
    var values = $(select).serialize();
    console.log (values);       // See if you get the serialized data in console.

    $.ajax({
        type: 'POST',
        url: "http://www.mysite.com/update_categories.php"
        data: values,
        success: function (data) {
            document.getElementById("my_div").innerHTML = data;
        }
    });
}

And FYI, Netscape event binding model is deprecated, you could use the cross browser event binding like this

查看更多
登录 后发表回答