为什么我总是得到这个ajax帖子到php的未定义响应?

时间:2016-10-30 18:40:14

标签: javascript php ajax

我在span元素上使用mouseover事件来启动对php页面的ajax post调用,但是我总是得到undefined,首先是responseText,当我使用一个简单的echo来获得响应时,现在当我使用responseXML时。有人可以解释一下为什么。 这是ajax代码:

var span = document.getElementsByTagName('span');

for (var i = 0; i < span.length; i++) {
   span[i].addEventListener("mouseover", showInformation, false);
}

function showInformation(event) {
    var xhr = new XMLHttpRequest();

    xhr.open("POST", "../includes/ajax_response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        content(xhr, event);
    }
};

xhr.send("uname=" + event.target.firstChild.textContent);
}

function content(xhr, event) {
    var info = document.getElementById('displayInformation');
    var xmlResponse = xhr.resopnseXML;
    var xmlDocumentElement = xmlResponse.documentElement;
    var message = xmlDocumentElement.firstChild.data;
    info.innerHTML = message;
    info.style.visibility = "visible";
    event.target.addEventListener("mouseout", function() {
    document.getElementById('displayInformation').style.visibility = "hidden";
    }, false);
}

这是php代码:

$username = $_POST['uname'];
$query = "SELECT id, joined FROM users WHERE username = '{$username}' LIMIT 1";
$first_result = Database::getInstance()->query($query);
if ($first_result->num_rows == 1) {
    foreach ($first_result as $first) {
        $id = $first['id'];
        $joined = $first['joined'];
    }
}
$first_result->free();

$query = "SELECT COUNT(message) AS count FROM blogs WHERE user_id = '{$id}'";
$results = Database::getInstance()->query($query);
if ($results) {
    foreach ($results as $result) {
        $number = $result['count'];
    }
}

header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
        echo "joined: {$joined}";
        echo "number of posts: {$number}";
echo '</response>';

这是带有xml的php的版本,我厌倦了更简单的版本  $username = $_POST['uname']然后echo $username,但始终是响应 未定义。

1 个答案:

答案 0 :(得分:1)

我读过您的代码一次,似乎没有任何重大错误。但是,我发现了这个小错误:

var xmlResponse = xhr.resopnseXML;

responseXML的拼写错误..也许这是导致xmlResponse未定义的原因?