【问题标题】:Why do I always get undefined response with this ajax post to php?为什么我总是在这个 ajax 帖子到 php 时得到未定义的响应?
【发布时间】:2017-03-12 22:54:15
【问题描述】:

我在 span 元素上使用 mouseover 事件来启动对 php 页面的 ajax 发布调用,但我总是未定义,首先是 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,但总是响应是 未定义。

【问题讨论】:

    标签: javascript php ajax


    【解决方案1】:

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

    var xmlResponse = xhr.resopnseXML;
    

    responseXML 的拼写不正确.. 也许这就是导致 xmlResponse 未定义的原因?

    【讨论】:

    • 哇,简直不敢相信这个错误。谢谢,这解决了 xml 的问题,但我仍然遇到 responseText 的问题,但我会在明天看到
    • 可能是另一个拼写错误? :-)
    猜你喜欢
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 2016-07-31
    • 2013-10-22
    • 2016-07-08
    相关资源
    最近更新 更多