我的阿贾克斯不起作用



我今天开始学习Ajax。 我试图按照如何使用 AJAX 的步骤进行一些练习,但不幸的是它不起作用,我不知道问题出在哪里,因为我在控制台.log中没有得到任何警告。

我有一个示例.xml在我的根文件夹中,我尝试从中获取数据。

这就是我所做的。 谢谢!

		function getXMLHttpRequest(){
	var xhr = null;

if(window.XMLHttpRequest || window.ActiveXObject){
	if(window.ActiveXobject){
	try{
	xhr = new ActiveXobject("Msxml2.XMLHTTP");
}catch(e){
	xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}else{
	xhr = new XMLHttpRequest();
}

}else{
	alert("Votre navigateur ne supporte pas l'objet XMLHttpRequest");
}

return xhr;
}
function request(callback){
	var xhr = getXMLHttpRequest();

xhr.onreadystatechange = function(){
	if(xhr.readyStae == 4 && (xhr.status == 200 || xhr.status == 0)){
	callback(xhr.responseXML);
}
}

xhr.open("GET", "example.xml", true);
xhr.send(null);    
}
function readData(oData){
	var node = oData.getElementsByTagName("soft");
var ul = document.createElement("ul");
var li, content;

for(let i = 0; i < node.length; i++){

	li = document.createElement("li");      
	content = document.createTextNode(node[i].getAttribute("name"));
li.appendChild(content);
ul.appendChild(li);
}
document.getElementById("output").appendChild(ul);
}
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>ajax</title>
</head>
<body>
	<p>
		<button onclick="request(readData);">Afficher les données</button>
	</p>
	<div id="output">
		
	</div>
</body>
</html>

你的代码中有拼写错误。

xhr.onreadystatechange = function(){
if(xhr.readyStae == 4 && (xhr.status == 200 || xhr.status == 0)){
callback(xhr.responseXML);
}
}

它应该是xhr.readyState == 4的,而不是xhr.readyStae == 4的。

xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)){
callback(xhr.responseXML);
}
}

最新更新