我正试图通过Ajax将多选列表框中的值传递给PHP。我在Jquery和JSON中看到了一些例子,但我正试图用简单的旧javascript(Ajax)来实现这一点。以下是我到目前为止(简化)的内容:
Ajax:
function chooseMultiEmps(str)
{
var mEmpList2 = document.getElementById('mEmpList'); //values from the multi listbox
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//specific selection text
document.getElementById('info').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myPage.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var queryString = "&mEmpList=" + mEmpList; //query string should have multiple values
xmlhttp.send(queryString);
}
我可以运行alert(mEmpList)
并在各个消息框中获得每个值,但是当我检索并回显$_POST['mEmpList']
时,我只获得第一个值。此外,当我alert(queryString)
时,我只得到一个值。
我认为我需要创建一个逗号分隔的数组,然后将其传递到查询字符串中。从那里,我可以使用PHP内爆/爆炸特性来分离值。如有任何协助,我们将不胜感激。
此处:
for (var i = 0; i < mEmpList2.options.length; i++) //loop through the values
var mEmpList = mEmpList2.options[i].value; //create a variable to pass in string
您正在一次又一次地重新定义mEmpList,这意味着只有最后一个值是发送
你可以做:
var mEmpList = '';
for (var i = 0; i < mEmpList2.options.length; i++) { //loop through the values
mEmpList = mEmpList +','+ mEmpList2.options[i].value; //create a variable to pass in string
}
此外,您的queryString
不正常,不需要&
var queryString = "mEmpList=" + mEmpList;
这样,在结束时,您将使用逗号,
分隔所有值
在PHP
中,您可以使用分解来循环每个值:
<?php
$string = explode(',' $_GET['mEmpList']);
for($i=1; $i<count($string); $i++){
echo $string[$i]."<br />";
}
?>