javascript提示符已发送到php,但输出为空

javascript提示符已发送到php,但输出为空,javascript,php,ajax,xmlhttprequest,Javascript,Php,Ajax,Xmlhttprequest,我试图通过使用ajax单击其下方的“+”按钮,将一个类别添加到类别下拉列表中,但我的下拉列表却一直消失 HTML代码如下 <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> <script> function addCategory()

我试图通过使用ajax单击其下方的“+”按钮,将一个类别添加到类别下拉列表中,但我的下拉列表却一直消失

HTML代码如下

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script>
function addCategory()
{
var category = prompt("Please enter new category: ", "");

if (category != null){
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    } else { 
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){// && xmlhttp.status==200) {
            document.getElementById("category").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","add_category.php?category="+category,true);
    xmlhttp.send();
}
}
</script>
<script language="javascript" src="calendar/calendar.js"></script>
</head>
<body>
<?php 
include ('db_conn.php');
session_start();

if(!empty($_REQUEST['event'])){
    $event = $dbc->prepare("SELECT * FROM `COO_DEF_EVENT` WHERE EVENT_ID = :eventid;");

    try{
        $event->bindParam(':eventid', $_REQUEST['event']);

        $event->execute();

        $eventdet = $event->fetch(PDO::FETCH_ASSOC);

    }catch(PDOException $ex){
        echo 'Error getting event data';
    }

    echo '<form id="form1" name="form1" method="post" action="editEvent.php">';
}else{
    echo '<form id="form1" name="form1" method="post" action="addEvent.php">';
}
?>  
Category:
<div id="category"><select name="categorydpl" id="categorydpl">
              <?php       
              $categorySQL = $dbc->prepare("SELECT * FROM `CATEGORY` WHERE USER_ID = :userid; ");

                try{
                    $categorySQL->bindParam(':userid', $_SESSION["userid"]);

                    $categorySQL->execute();

                    $categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);

                    foreach ($categoryList as $category){
                        echo '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
                    }

                }catch(PDOException $ex){
                    echo 'Error getting data';
                }
                ?>
            </select></div><button onClick="addCategory()">+</button>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit"
                value="Submit" /><button onClick="location.href ='index.php';">Cancel</button>
</form>
</body>
</html>
PHP文件

<?php
include ('db_conn.php');
session_start();

$category = $_GET['category'];
$print='category entered: '.$category;

$sql = $dbc->prepare("INSERT INTO `COO_CATEGORY` (`USER_ID`, `CATEGORY_NAME`) VALUES (:userid, :category_name);");

try{
    $sql->bindParam(':userid', $_SESSION["userid"]);
    $sql->bindParam(':category_name', $category);

    $sql->execute();

}catch (PDOException $ex){
echo 'Insertion failed. Please try again';
}

 $categorySQL = $dbc->prepare("SELECT * FROM `COO_CATEGORY` WHERE USER_ID = :userid;");

try{
    $categorySQL->bindParam(':userid', $_SESSION["userid"]);

    $categorySQL->execute();

    $categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);

    $print .= '<select name="categorydpl" id="categorydpl">';
    foreach ($categoryList as $category){
    $print.= '<option value="'.$category['CATEGORY_ID'].'">'.htmlspecialchars($category['CATEGORY_NAME']).'</option>';
}
$print.='</select>';

}catch(PDOException $ex){
echo 'Error getting data';
}
echo $print;
?>
当我通过键入…/add_category.php?category=sad打开php时

页面将显示

输入类别:sad,然后是插入sad的下拉列表

但是当我尝试使用html文件时,单击加号按钮并输入任何值后,dropdownlist将消失

有什么建议吗


提前感谢

用jQuery试试。在html文件中

$.ajax(
        {
            type: 'GET',
            url: 'add_category.php',
            dataType: 'json',
            data: {'category' : category},
            success:
                function(answer){
                    $('#categorydpl').empty();
                    answer && answer.forEach(function(entry){
                        $('#categorydpl').append(new Option(entry['id'], entry['name']));
                    })
                },
            error: 
                function(){
                    console.log('Error');
                }
        }
      );
在php文件中

$categoryList = $categorySQL->fetchAll(PDO::FETCH_ASSOC);
foreach ($categoryList as $category){
    $result[] = array('id' => $category['CATEGORY_ID'], 'name' => htmlspecialchars($category['CATEGORY_NAME']));
}
echo json_encode($result);

提交按钮提交表单。提交表单将重新加载页面


使用确保您没有执行跨站点请求。当使用ajax调用在不同域上调用页面时,默认情况下浏览器不允许将其作为安全措施。

是否使用Firebug或类似工具检查了xmlhttp调用的响应?我刚刚尝试在firefox上使用它。但它没有显示任何东西。我想这是因为我每次都被重定向到错误页面。我正在000webhost.com上进行测试。如果它没有显示任何内容,那么就没有进行呼叫,这很奇怪,因为您的divcategory正在更新。您可以将响应文本记录到Console.log中吗?另外,请查看firebug网络选项卡,它非常适合调试此类问题:好的,我再次尝试并检查了网络选项卡。在…/add_category.php?category=sad下,在params选项卡下,它显示category sadWell,然后您应该跟踪xmlhttp.responseText,看看确切的值是什么。还有,为什么要注释掉&&xmlhttp.status==200部分呢?但是如果jQuery还没有包括在内,那么当vanilla js will do.xmlhttp.status为0时就有点过分了,我检查了那些有同样问题的部分,大多数情况下,当status为0时,是跨站点请求。但是我的所有文件都在同一个服务器domian文件夹中。请仔细检查它们是否在同一个服务器上,然后尝试用绝对URL替换所有文件,以确保安全。