【问题标题】:javascript prompt sent to php but output emptyjavascript提示发送到php但输出为空
【发布时间】:2014-08-18 06:47:26
【问题描述】:

我正在尝试通过使用 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 文件时,单击加号按钮并输入任何值后下拉列表将消失。

有什么建议吗?

提前致谢!!!

【问题讨论】:

  • 您是否检查过使用 Firebug 或类似工具的 xmlhttp 调用的响应是什么?
  • 我刚刚尝试在 Firefox 上使用它。但它没有显示任何东西。我认为这是因为我每次都被重定向到错误页面。我正在 000webhost.com 上进行测试。
  • 如果它没有显示任何内容,那么就没有进行调用,这很奇怪,因为您的 div#category 正在更新。您可以 Console.log() 响应文本吗?另外,查看 firebug 网络选项卡,它非常适合调试此类问题:getfirebug.com/network
  • 好的,我再次尝试并检查了网络选项卡。在 .../add_category.php?category=sad 下,在 params 选项卡下,它显示类别 sad
  • 好吧,那么你应该跟踪 xmlhttp.responseText,看看那个确切的值是什么。另外,为什么你把“&& xmlhttp.status==200”部分注释掉了?

标签: javascript php ajax xmlhttprequest


【解决方案1】:

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

使用&lt;button type="button"&gt;

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 但是如果 jQuery 还没有被包括在内,那么当 vanilla js 可以做的时候就有点矫枉过正了。
    【解决方案3】:

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

    【讨论】:

    • xmlhttp.status 为 0,我检查了那些有同样问题的,大多数发生在状态为 0 时是跨站点请求。但是我所有的文件都在同一个服务器、域、文件夹上。
    • 仔细检查它们是否存在,并尝试用绝对网址替换所有内容,以确保。
    猜你喜欢
    • 2011-04-14
    • 1970-01-01
    • 2021-11-12
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多