返回TypeError:document.getElementById(...)为null

时间:2014-02-25 14:09:17

标签: javascript php jquery ajax

我有一个用于从我的php页面获取数据的Ajax代码,但它没有将任何数据返回给Ajax,返回null值。

function getType(str){
$("#selectCat").html("Select the Catagory of " +str);

    if (str.length == 0){ 
                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('category').innerHTML = xmlhttp.responseText;
    }
}
 xmlhttp.open("GET","OrderItem.php?q="+str,true);
 xmlhttp.send();
 }

这是我的PHP代码

session_start();
    $currentUser = $_SESSION["userID"];
    include("include/dbcommon.php");
$value = $_GET['q'];
//echo $value;
    $sqlString = "";
   if($value == "dish"){
        $sqlString = "select name from dishcategory";
       }else if($value == "drinks"){
        $sqlString ="select name from drinkscategory";
   }else if($value == "desserts"){
        $sqlString = "select name from dessertcategory";
}
    $rs = customQuery($sqlString);
while($data= db_fetch_array($rs)){

    echo "<option value='".$data['name']."'>".$data['name']."1</option>";

}

和我的HTML部分

<TABLE style="WIDTH:85%" cellSpacing=1 cellPadding=1 width="75%">
  <TBODY>
    <TR>
       <TD>&nbsp;<STRONG>Ordered Item Category</STRONG></TD></TR>
     <TR>
       <TD>&nbsp;<input type="Radio" name="itemType" id="" class="selebtn" value="dish" onClick="getType(this.value)"> Dish <input type="Radio" name="itemType" id="" class="selebtn" value="drinks" onClick="getType(this.value)"> Drinks <input type="Radio" name="itemType" id="" class="selebtn" value="desserts" onClick="getType(this.value)"> Desserts
       </TD></TR></TBODY></TABLE>
     <TABLE>
  <TBODY>
    <TR><TD><span id="selectCat"></span></TD></TR>
    <TR><TD><span id="selePan"><select name="itemcat" id="itemcat"><option value="">select</option><span id="category"></span></select></span></TD></TR>
</TBODY>
     </TABLE>

请我无法得到为什么它返回空值? 提前谢谢

1 个答案:

答案 0 :(得分:3)

您的HTML无效。您不能将span元素作为select的子元素。您的问题可能是由于浏览器执行错误恢复并丢弃了span元素(这肯定是Chrome对代码的反应)。

使用a validator