Javascript 从HTML操作XML上的文本节点
编程新手,因此这对大多数人来说可能是一个简单的解决方案。话虽如此,我在通过HTML代码操纵XML节点时遇到了困难,下面是我试图实现的目标Javascript 从HTML操作XML上的文本节点,javascript,html,xml,Javascript,Html,Xml,编程新手,因此这对大多数人来说可能是一个简单的解决方案。话虽如此,我在通过HTML代码操纵XML节点时遇到了困难,下面是我试图实现的目标 将“比利时华夫饼”替换为“英式松饼”,并用新的值更改价格、说明和卡路里 现在,通过删除一个节点并添加一个新的节点方法,将每个食品的价格降低5% 我的函数只是没有处理从XML文件加载的现有数据,我不太确定如何进行第二步 XML文件 华夫饼 $5.95 我们的两个著名的比利时华夫饼干,里面有很多真正的枫糖浆 650 草莓比利时华夫饼干 $7.95 覆盖草莓和鲜
华夫饼
$5.95
我们的两个著名的比利时华夫饼干,里面有很多真正的枫糖浆
650
草莓比利时华夫饼干
$7.95
覆盖草莓和鲜奶油的淡比利时华夫饼干
900
浆果比利时华夫饼干
$8.95
比利时华夫饼干,上面覆盖着各种新鲜浆果和鲜奶油
900
法式吐司
$4.50
用我们自制的酸面包做成的厚片
600
家庭式早餐
$6.95
两个鸡蛋,培根或香肠,土司,还有我们一直受欢迎的炸土豆条
950
您没有正确配置XMLHttpRequest
对象。您没有设置“success”回调函数,而是在发送请求后,代码立即尝试访问结果,而不等待请求处理,因此此时没有返回值
XHR请求是异步的,这意味着我们不知道它们需要多长时间才能返回。我们必须设置一个回调,无论何时发生,都可以调用它
设置XHR的一般方法如下:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","breakfast.xml",false);
// Set up callback functions to handle the outcomes of the request
xmlhttp.addEventListener("load", transferComplete);
xmlhttp.addEventListener("error", transferFailed);
// Only after the XHR has been completely configured can you send the request
xmlhttp.send();
// This function will be called when there is a successful
// response from the request.
function transferComplete(evt){
// Only when this function is called (automatically by the XHR)
// is it safe to access: xmlhttp.responseXML and only from within
// this function can you call it (unless you assign it to a higher
// scoped variable, but that wouldn't be a good idea because outside
// of this function, you can't be sure that the assignment has taken place.
// Also, instead of multiple document.write() statements, just
// populate an existing DOM element with the contents of
// the response.
}
// This function will be called when there is an error
function transferFailed(evt){
console.log("Something went wrong!");
}
有关设置XMLHttpRequest的更多详细信息,请参见
注意事项:
- 所有浏览器都本机支持的
对象 很多年了。除非您仍然支持IE8,否则您可以删除 整个if语句,只需使用:XMLHttpRequest
xmlhttp=new XMLHttpRequest()代码>
仅在将动态内容写入新文档时使用 窗户。相反,只需修改现有DOM元素的内容即可document.write()
if(window.XMLHttpRequest)
{
xmlhttp=新的XMLHttpRequest();
}否则{
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
open(“GET”,“breaken.xml”,false);
//这只会发送请求,不会填充响应
xmlhttp.send();
//要获取文件内容,需要为load event添加事件侦听器
addEventListener(“加载”,函数(evt){
xmlDoc=xmlhttp.responseXML;
文件。填写(“”);
var x=xmlDoc.getElementsByTagName(“食品”);
对于(i=0;i