Javascript 使用 AJAX 通过 POST 请求发送 HTML 表单多个 <select> 框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14766103/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending HTML Form Multiple <select> box via POST request with AJAX?
提问by Scott Kaiser
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:
我有一个带有多选框的 html 表单。我不知道如何通过 post 请求使用 AJAX 将值发送到我的 php 应用程序。如果我使用 GET 请求并使用单个选择框,它就可以正常工作,但当我使用多个选择框时就不行了。这个想法是让用户保持控制(或使用 mac 命令)并选择一个或多个类别。根据选择的类别将决定使用 AJAX 显示哪些其他表单选项。选择框如下所示:
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:
我的 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);
}
回答by Ian
You'll have to generate the query string to send in the POST on your own. Here's the HTML tag to use:
您必须自己生成要在 POST 中发送的查询字符串。这是要使用的 HTML 标记:
<select multiple name="categories[]" onchange="sendCategories(this);">
And the Javascript function:
和 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);
}
Note that I changed the event from onclickto 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.
请注意,我将事件从 更改onclick为onchange,但这取决于您是否希望在单击元素时运行此函数,或者它的值是否真正发生更改……它可以减少一些不必要的调用。
This should generate a querystring that is normally used for sending values for a <select>with multiple options selected.
这应该生成一个查询字符串,该字符串通常用于为<select>选择了多个选项的a 发送值。
Here's a jsFiddle that demonstrates how the querystring is being generated here: http://jsfiddle.net/kKWQM/
这是一个 jsFiddle,它演示了如何在此处生成查询字符串:http: //jsfiddle.net/kKWQM/
回答by Salman
You can do something like this,
你可以做这样的事情,
<select multiple name="categories[]" onclick="sendCategories(this)">
And Make AJAX using JQuery,
并使用 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;
}
});
}
And FYI, Netscape event binding model is deprecated, you could use the cross browser event binding like this
仅供参考,Netscape 事件绑定模型已弃用,您可以像这样使用跨浏览器事件绑定
回答by user3155285
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:
您可以根据需要使用 JS 字符串和数组函数来实现该解决方案。实际上,您需要发送到 Apache 的字符串应包含如下模式:
xxx[]=a&xxx[]=b&xxx[]=c
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.
其中 SELECT 元素的名称xxx[]在您的表单中,a、b 和 c 是用户选择的三个值。
So yes, you are repeating a key name as many times as the user selected a different option in the SELECT.
所以是的,您重复一个键名的次数与用户在 SELECT 中选择的不同选项一样多。
In JS you can use an array of selected options:
在 JS 中,您可以使用一组选定的选项:
selected_options.join("&xxx[]=") to produce that pattern.
回答by mockaroodev
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:
jQuery 应该让你更容易做到这一点。在包装的选择上调用 .val() 会返回所选值的数组。您只需将这些发布到服务器:
HTML:
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:
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
});
});
});

