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

时间:2014-08-18 06:47:26

标签: 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()
{
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 = sad

页面将显示

&#34;输入的类别:悲伤&#34;然后是一个带有悲伤插入的下拉列表。

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

有什么建议吗?

提前致谢!!!

3 个答案:

答案 0 :(得分:0)

尝试使用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);

答案 1 :(得分:0)

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

使用<button type="button">

答案 2 :(得分:0)

确保您没有进行跨网站请求(http://en.wikipedia.org/wiki/Same-origin_policy)。使用ajax调用在不同域上调用页面时,浏览器默认不允许它作为安全措施。