使用AJAX通过POST请求发送HTML表单多个<select>框?</select>

时间:2013-02-08 05:12:29

标签: javascript html ajax arrays forms

我有一个带有多个选择框的html表单。我无法弄清楚如何使用AJAX通过发布请求将值发送到我的php应用程序。如果我使用GET请求并使用单个选择框,但是当我使用多选框时,它可以正常工作。这个想法是让用户保持控制(或使用mac命令)并选择一个或多个类别。根据选择的类别,将确定使用AJAX显示哪些其他表单选项。选择框如下所示:

修改:已解决

<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>

我的javascript函数如下所示:

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 个答案:

答案 0 :(得分:4)

您必须自己生成要在POST中发送的查询字符串。这是要使用的HTML标记:

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

和Javascript功能:

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);
}

请注意,我已将事件从onclick更改为onchange,但是您是否希望在单击元素时运行此函数,或者其值是否真正更改,这取决于您...它可以减少一些不必要的电话。

这应生成一个查询字符串,通常用于发送<select>的值,并选择多个选项。

这是一个jsFiddle,它演示了如何在这里生成查询字符串:http://jsfiddle.net/kKWQM/

答案 1 :(得分:2)

你可以这样做,

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

使用JQuery制作AJAX,

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;
        }
    });
}

和FYI,Netscape事件绑定模型已弃用,您可以使用跨浏览器事件绑定,如this

答案 2 :(得分:1)

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.

答案 3 :(得分:0)

jQuery应该让你更容易。在包装的select上调用.val()会返回所选值的数组。您只需将这些发布到服务器:

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
        });
    });
});