通过ajax和javascript将xml数据提取到div中

时间:2013-04-29 14:33:20

标签: javascript xml ajax

构建聊天应用程序,我正在尝试将所有登录用户提取到ID为“chat_members”的div中。但是没有任何东西出现在div中我已经验证了xml文件结构是正确的但是我和ajax一起使用的javascript不仅仅是工作。 我认为问题出在代码区域,我试图在for循环中假脱机xml数据。

XML数据样本:

<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>

的Javascript

<script language="javascript">

// JavaScript Document


var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;

function startChat() {
    getOnlineMembers();
}   

// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
    return new XMLHttpRequest();
}
else if(window.ActiveXObject){
    return new ActiveXObject("Microsoft.XMLHTTP");
} else{
        //alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");  
        document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}

function getOnlineMembers(){
    if(getMember.readyState == 4 || getMember.readyState == 0){
        getMember.open("GET", "get_chat.php?get_member", true);
        getMember.onreadystatechange = memberReceivedHandler;
        getMember.send(null);
    }else{
            // if the connection is busy, try again after one second  
            setTimeout('getOnlineMembers()', 1000);
    }
}



function memberReceivedHandler(){
    if(getMember.readyState == 4){
        if(getMember.status == 200){

            var chat_members_div = document.getElementById('chat_members');
            var xmldoc = getMember.responseXML;
            var members_nodes = xmldoc.getElementsByTagName("member"); 
            var n_members = members_nodes.length;
            for (i = 0; i < n_members; i++) {
                chat_members_div.innerHTML += '<p><a href="' + members_nodes[i].childNodes.nodeValue + '">' + members_nodes[i].childNodes.nodeValue + '</a></p>';
                        chat_members_div.scrollTop = chat_members_div.scrollHeight;
                    }

            mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds

        }
    }   
}


</script>

HTML页面

<body onLoad="javascript:startChat();">

  <!--- START: Div displaying all online members --->
  <div id="chat_members">


  </div>
  <!---END: Div displaying all online members --->

</body>

我是ajax的新手,非常感谢您对此有所帮助。 谢谢!

2 个答案:

答案 0 :(得分:0)

要解决此问题:

- 使用HTTP Fiddler之类的HTTP分析器。看看通信 - 你的页面调用服务器并正确获取你想要的代码,而不是某种类型的HTTP错误?

- 检查您的IF语句,并确保它们被正确括起来。当我看到:

if(getMember.readyState == 4 || getMember.readyState == 0){

我看到混乱。它应该是:

if( (getMember.readyState == 4) || (getMember.readyState == 0)){

它可能没什么区别,但绝对肯定是好的。

- 在IF之后对你的javascript子句进行某种检查,以确保程序流正常执行。如果您没有调试器,只需在其中粘贴一个警告框。

答案 1 :(得分:0)

您必须在检查响应状态之前发送xmlhttp请求:

function getOnlineMembers(){
        getMember.open("GET", "get_chat.php?get_member", true);
        getMember.onreadystatechange = memberReceivedHandler;
        getMember.timeout = 1000; //set timeout for xmlhttp request
        getMember.ontimeout = memberTimeoutHandler;
        getMember.send(null);
}

function memberTimeoutHandler(){
        getMember.abort(); //abort the timedout xmlhttprequest
        setTimeout(function(){getOnlineMembers()}, 2000);
}

function memberReceivedHandler(){
    if(getMember.readyState == 4 && getMember.status == 200){

            var chat_members_div = document.getElementById('chat_members');
            var xmldoc = getMember.responseXML;
            var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); 
            var n_members = members_nodes.length;
            for (i = 0; i < n_members; i++) {
                chat_members_div.innerHTML += '<p><a href="' + members_nodes[i].childNodes.nodeValue + '">' + members_nodes[i].childNodes.nodeValue + '</a></p>';
                chat_members_div.scrollTop = chat_members_div.scrollHeight;
            }
            mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
    }   
}

要防止缓存响应,您可以尝试:

getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);

通过以下方式检查responseXML是否为空:

console.log(responseXML);

在选择childNodes之前,您可能还需要选择xml响应的根节点:

var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document

希望这会有所帮助