Javascript和XML按钮

时间:2015-11-03 19:38:50

标签: javascript html xml dom

您好我已经通过html创建了一个按钮,我试图在单击按钮时显示一个XML页面。我需要通过javascript来做到这一点,但它似乎并没有为我工作。

我的HTML:

<input type="button" value="Shop 1" id ="one">
<input type="button" value="Shop 2" id ="two">
<input type="button" value="Put Selected Pictures in Cart" id ="three">

我的JavaScript:

 function getData(filename) { env = new XMLHttpRequest(); env.open("GET",            filename); } 

 function init()
{

 document.getElementById('one').onclick = function(){ getData('shop1.xml'); }
 document.getElementById('two').onclick = function(){ getData('shop2.xml'); }
}

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

由于XMLHttprequests的性质是异步的,您应该在回调函数中处理检索到的数据(或者您可以通过指定env.open("GET",url, true)使其同步。您的新getData函数将如下所示:< / p>

function getData(url, callback) { 
  var env = new XMLHttpRequest(); 
  env.onload = function() {
    callback(env.response);
  };
  env.open("GET", url); 
}

你可以按如下方式使用它:

var one = document.getElementById('one'),
    two = document.getElementById('two');

one.onclick = function(){
  getData('shop1.xml', function(response) { 
     /* do whatever you want with the response XML */ 
  });
}
two.onclick = function(){
  getData('shop2.xml', function(response) { 
     /* do whatever you want with the response XML */ 
  });
}

有关详细信息,请参阅MDN: Using XMLHttpRequest。请注意,这只是将XMLdoc作为字符串;如果您需要将其作为XML树使用,则需要使用DOMParser API