【问题标题】:Javascript Array Passed to PHP Through Ajax通过 Ajax 传递给 PHP 的 Javascript 数组
【发布时间】:2012-08-27 21:35:20
【问题描述】:

我正在尝试通过 Ajax 将多选列表框中的值传递给 PHP。我在 Jquery 和 JSON 中看到了一些示例,但是我试图用普通的旧 javascript (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 implode/explode 功能来分离这些值。任何帮助将不胜感激。

【问题讨论】:

    标签: php ajax arrays


    【解决方案1】:

    这里:

    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不行,不需要&amp;

    var queryString = "mEmpList=" + mEmpList;
    

    这样最后你会得到所有用逗号分隔的值,

    PHP 中,您可以使用explode 循环每个值:

    <?php
        $string = explode(',' $_GET['mEmpList']);
        for($i=1; $i<count($string); $i++){
            echo $string[$i]."<br />";
        }
    ?>
    

    【讨论】:

    • 对于其他人,要仅获取多列表框中的选定值,您需要添加: if (mEmpList2.options[i].selected) {... concatenate comma... } javascript for 循环之间
    猜你喜欢
    • 2015-09-11
    • 1970-01-01
    • 2011-10-24
    • 2020-04-01
    • 1970-01-01
    • 2010-10-17
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多