如何使用php从XML文件加载数据,并使用javascript将其显示在html页面中


How to load data from an XML file using php to show it in an html page with javascript

我正在为我的编程类赋值。我需要显示一个包含两列(name和lastname)的朋友列表的表。这些数据存储在一个XML文件中,如下所示:

<?xml version='1.0' standalone='yes'?>
<amigos>
 <amigo>
  <nombre>Alejandra</nombre>
  <apellido>Ponce</apellido>
 </amigo>
 <amigo>
  <nombre>Dalia</nombre>
  <apellido>Gordon</apellido>  
 </amigo>

我用php检索这些数据,如下所示:

<table width="200" border="1">
 <tr align="center">
    <td>NOMBRE</td>
    <td>APELLIDO</td>
 </tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
    echo '<tr>';
    echo '<td>',$amigo->nombre,'</td>';
    echo '<td>',$amigo->apellido,'</td>';
    echo '</tr>';
}
?>

我用javascript语言编写的函数调用这个php文件。我正在用ajax做这个家庭作业。我的javascript文件如下所示:

var xmlHttp;
function  createXmlHttpRequestObject() {
    if(window.ActiveXObject){
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(e)
        {
            xmlHttp=false;
        }
    }
    else{
        try{
            xmlHttp = new XMLHttpRequest();
        }catch(e)
        {
            xmlHttp=false;
        }
    }
    if(!xmlHttp)
        alert('Can't connect to the host');
    else
        return xmlHttp; 
}
function cargarAmigos(url) 
{
  if(url=='')
  {
    return;
  }
  xmlHttp=createXmlHttpRequestObject();
  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = procesarEventos;
  xmlHttp.send(null);
}
function cargar(url) 
{
  if(url=='')
  {
    return;
  }
  xmlHttp=createXmlHttpRequestObject();
  xmlHttp.open("GET", url, true);
  xmlHttp.onreadystatechange = procesarEventos;
  xmlHttp.send(null);
}
function procesarEventos()
{
  if(xmlHttp.readyState == 4)
  {
      document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
  } 
}

我在一个html文件中使用这个javascript文件。我在按钮的onclick事件中调用函数cargar(),如下所示:

<body>
 <div id="listaAmigos" > 
  Lista amigos
 </div>
 <button onclick="cargarAmigos('procedimiento.php');">Lista Amigos    Ajax</button>
</body>

问题是代码不起作用。我的意思是,这些名字根本没有显示在表中。实际上这张桌子没有出现。我很确定这个错误不在代码中,因为它上周就开始工作了,从那以后我再也没有更改过代码。但今天我加载html页面只是为了"好玩",它没有显示我的朋友列表。所以我决定打开另一个使用相同算法的项目,但这个项目也不起作用。我已检查所有文件是否都在同一个文件夹中。我已经检查了我的xammp服务器,它的apache和mysql服务都在运行。我不知道我可以做什么"事情"来引起这个问题。

任何帮助都将不胜感激。

看起来应该转义此行中的'字符:

alert('Can't connect to the host');

即像一样重写

alert("Can't connect to the host");

你可以看到有一个错误,即使只是通过查看堆栈溢出上的格式:)

请参考这个问题,了解为什么它会这样工作:什么时候在JavaScript中使用双引号或单引号?