【问题标题】:Return Multiple checkbox in AJAX response在 AJAX 响应中返回多个复选框
【发布时间】:2013-02-15 22:32:39
【问题描述】:

我有 2 个 php 页面,Page1 包含(html + javascript + php 代码),page2 仅包含 php 代码。

所以,在 page1 内,有一个下拉列表包含许多值,如果我选择其中一个,AJAX 代码会像这样将值传递给 page2.php:

如果我用下拉菜单替换复选框输入,脚本可以完美运行,但在这种情况下,它不起作用。

目的是将 page2 的结果显示为 page1 上的复选框。 有什么想法吗?

Page1.php:

HTML 代码:

  <select onChange="getdids(this.value)" id="groupSelect" name="groupSelect" >
        <option value="0">xxx</option>
            <option value="1">yyy</option>
            <option value="2">zzz</option>
            <option value="3">vvv</option>
  </select> 

  <input type="checkbox" id="alldids" name="alldids" value="0">did<br>

AJAX 代码:

  <script>
  function getdids(str)
  {
    if (str=="")
      {
       document.getElementById("alldids").innerHTML="";
       return;
      }
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
       {
        document.getElementById("alldids").innerHTML=xmlhttp.responseText;
       }
    }
  xmlhttp.open("GET","page1.php?groupName="+str,true);
  xmlhttp.send();
 }


 </script>

Page2.php:

PHP 代码:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Get dids</title>
    </head>

    <?php
    require_once('../functions.php');
    include('../variables.php');
    $didGrpName=$_GET['groupName'];
    $didGrpId=GroupId($table_groups,$didGrpName);
    $x=array();
    $x=showDidOfGroup($didGrpId);

    $i=1;
    while($i <= $x[$i]){ ?>
    <input type="checkbox" value="<?php echo $x[$i]; ?>"><?php echo $x[$i]; ?><br>
    <?php $i++; } ?>

    <body>
    </body>
    </html> 

【问题讨论】:

  • 看起来应该可以了。问题是什么?这其中的哪一部分不起作用?
  • 我在 page1 中看不到复选框
  • 如何使用 Jquery 从 php 文件发送和获取数据?我是 Jquery 和 AJAX 的新手

标签: php ajax checkbox responsetext


【解决方案1】:

您永远不会为您的复选框调用getdids,并且一组复选框的值比(非多个)选择元素的值更复杂。

从复选框组构造application/x-www-url-form-encoded数据的算法是:

Create an empty array
For each "checkbox" in "group of checkboxes with same name":
    if checkbox.checked:
        append encodeURIComponent(name) + "=" + encodeURIComponent(checkbox.value) to array
JOIN array with "&"

【讨论】:

  • 我不太清楚,我只需要将page2的结果显示为page1上的复选框,page2的结果是一个包含Mysql响应的数组。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-06
  • 2019-12-19
  • 2021-01-14
  • 2019-05-26
  • 2015-05-04
相关资源
最近更新 更多