1

我正在尝试通过 ajax 从服务器检索 xml 文件,但无法解析它。我不知道我做错了什么。当我调用 getFriends.php 时,它会很好地打印 xml。这是ajax代码:

<!DOCTYPE>
<html>
<head>
<title>Ajax Sample</title>

<script type="text/javascript">

function getFriendsList(MemberId) {

    var xmlhttp;

    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
    }
    else {
        // code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {

    if (xmlhttp.readyState==4 && xmlhttp.status==200) {

            var xmlDoc = xmlhttp.responseXML;
            var friendElements = xmlDoc.getElementsByTagName('friend');

            for (var x=0; x<friendElements.length; x++) {
                // We know that the first child of show is title, and the second is rating
                var id = showElements[x].childNodes[0].value;
                var name = showElements[x].childNodes[1].value;

                // Now do whatever you want with the show title and ratings
                document.write("hi");
          }

        }
    }

    xmlhttp.open("POST","getFriends.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("id=" + MemberId);

}

</script>

</head>

<body>

    <input name="ajax" type="button" onClick="getFriendsList(1)" value="Click for AJAX">
    <div style="background-color:#00FF99;" id="placehere">Here is where the update will occur.</div>
</body>
</html>

这是 getFriends.php 代码(用户类工作正常):

<?php
include('lib.php');
//$id = $_POST['id'];
$id=1;
$user = new User($id);

echo $user->getFriendsList();

?>
4

2 回答 2

2

您的 for 循环中有未定义的变量“showElements”。这两行:

var id = showElements[x].childNodes[0].value;
var name = showElements[x].childNodes[1].value;

应替换为:

var id = friendElements[x].childNodes[0].value;
var name = friendElements[x].childNodes[1].value;
于 2012-04-19T18:32:50.960 回答
0

使用 jquery 执行 ajax 调用既简单又轻松,请参阅http://api.jquery.com/jQuery.ajax/了解更多信息

于 2012-04-19T18:07:43.690 回答