H_MZ 2017-01-29 00:48 采纳率: 0%
浏览 30

Ajax和PHP中的复选框决定

This is my first post guys, please forgive me for any glaring posting errors. I'm attempting to create a checkbox in an html page but I would like to retrieve data from my .php page. At this point in my code it doesn't matter whether the box is checked or not, it shows the same answer (that it is) - any suggestions ??

HTML code

<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    try
      {
      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    catch (e)
      {
      alert("Your browser does not support AJAX!");
      return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
    {
    if(xmlHttp.readyState==4)
      {
      //alert(xmlHttp.responseText);
      document.getElementById("DisplayBox").innerHTML=xmlHttp.responseText;
      }
    }
  // start the query string
  var QueryString = "IceCream_Coating.php?";
  QueryString = QueryString + "checked=" + document.getElementById("checked").value;
  //alert(QueryString);
  xmlHttp.open("GET", QueryString, true);
  xmlHttp.send(null);
  }

</script></head>

<body>
<p>Is the box Checked</p>
<form id="myform" name="myform" method="POST">
<p><input type="checkbox" name="checked" id="checked" value="yesORno"></p>
   <input type="button" name="button" id="button" value="Decision" onclick="ajaxFunction();"/>
  </p>
</form>
  <p>
    <div id="DisplayBox">
    </div>
  </p>
</body>

PHP code

<?php

$value = $_GET['checked'];

if (isset($value)) {
    echo "Yes the box is checked.";
} else {
    echo "No, the box is not checked.";
}

?>
  • 写回答

1条回答 默认 最新

  • 撒拉嘿哟木头 2017-01-29 01:13
    关注

    You need to check if the checkbox is checked or not. Currently, you're just fetching the value that is set on the element, regardless if it's state.

    Try this:

    var QueryString = "IceCream_Coating.php?";
    
    if (document.getElementById("checked").checked) {
        // Only add the value if it is checked
        QueryString += "checked=" + document.getElementById("checked").value;
    }
    

    We also need to change the PHP code:

    <?php
    // We need to check if the parameter is set before trying to use it
    $value = isset($_GET['checked']) ? $_GET['checked'] : null;
    
    if ($value) {
        echo "Yes the box is checked.";
    } else {
        echo "No, the box is not checked.";
    }
    
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程