GET请求到.php后,AJAX responseText未定义

时间:2011-07-25 20:44:04

标签: php javascript html ajax responsetext

我正在尝试从mySQL数据库中提取设备列表,然后将其格式化为我的.php中的html select / option元素,然后我回显html字符串以插入到我的主页面中,但它不会将我回显的字符串返回给responseText。

这是我的.php:

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "admin";
$dbname = "devices";
    //Connect to MySQL Server
$con=mysql_connect($dbhost, $dbuser, $dbpass);
    //Select Database
mysql_select_db($dbname) or die(mysql_error());

$sql="SELECT DISTINCT device_name FROM device_graphs";
$result=mysql_query($sql, $con);

$responsetxt="Hello all :)";
$counter=0;
while($row = mysql_fetch_array($result))
{
    $responsetxt .= "<option value=$counter>$row[0]</option>";
    $counter++;
}

echo $responsetxt;

?>

我正在尝试根据我的数据库中列出的设备生成设备名称的下拉列表。当我在浏览器中打开.php文件时,它正确地回应。

function deviceDropdown(monNum, insideHTML)
{
var ajaxRequest;  // The variable that makes Ajax possible! 
try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        alert(ajaxRequest.responseText);
        ajaxresponse = ajaxRequest.responseText;
        alert(ajaxresponse);
        deviceDropdown_pt2(monNum, ajaxresponse, insideHTML);
    }
}
ajaxRequest.open("GET", "device_list.php", true);
ajaxRequest.send(null); 
}

ajaxresponse每次尝试时都是未定义的;它只会弹出2个空的javascript警告框。如果我在我的浏览器中只运行.php,我得到正确的输出回显到我的窗口,所以我不认为这是php的问题,除非有问题通过php通过ajax传递html。

以下是其余的下拉代码:

function deviceDropdown_pt2(monNum, ajaxresponse, insideHTML)
{
//Sets the action to occur when a selection is made in the device dropdown, 
//  in this case the properties dropdown menu
insideHTML=insideHTML + "<select onchange='propertiesDropdown(this.options[this.selectedIndex].value, " +  monNum + ")'>";  
insideHTML=insideHTML + "<option value=\"-1\">-Select a Device-</option>";
insideHTML = insideHTML + ajaxresponse; 
insideHTML=insideHTML + "</select>";
}

我的主要.js具有以下定义的var iframe=document.getElementById("bdy");和:

insideHTML="<table id=\"dashboard\" align=\"left\" valign=\"top\" border=\"0\">";
insideHTML=insideHTML + "<tr>";
insideHTML=insideHTML + "<td id=\"menu1\" width=\"800\">";
deviceDropdown("1", insideHTML);
insideHTML=insideHTML + "</td></tr>"; 
iframe.innerHTML=insideHTML;

1 个答案:

答案 0 :(得分:0)

您应该使用http://jquery.com/

您想要实现的目标的简单示例:

$.get('ajax/test.html', function(data) {
    $('.result').html(data);
    alert('Load was performed.');
});

您需要做的就是在标题中加入:

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script