Javascript提示发送到PHP,但输出为空


javascript prompt sent to php but output empty

我试图允许添加一个类别到类别下拉列表通过点击'+'按钮下面使用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;
?>

当我打开php输入…/add_category.php?类别=伤心

页面将显示

"category entered: sad "后面是一个插入sad的下拉列表。

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

任何建议吗?

提前感谢!!

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

使用<button type="button">

用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);

确保您没有做跨站点请求(http://en.wikipedia.org/wiki/Same-origin_policy)。当使用ajax调用不同域上的页面时,作为一种安全措施,浏览器默认不允许这样做。