Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  137] [ 1]  / answers: 1 / hits: 31355  / 11 Years ago, mon, august 26, 2013, 12:00:00

I need to load and read an XML file using JavaScript.



The following code works fine in Firefox, IE and Opera:



function loadXMLDoc(dname) {
var xmlDoc

// Internet Explorer
try {
xmlDoc = new ActiveXObject('Microsoft.XMLDOM')
}
catch (e) {
// Firefox, Opera, etc.
try {
xmlDoc = document.implementation.createDocument('', '', null)
}
catch (e) {
alert(e.message)
}
}

try {
xmlDoc.async = false
xmlDoc.load(dname)
return xmlDoc
}
catch (e) {
alert(e.message)
}

return null
}


But executing this code in Chrome gives me this error:




Object# has no method load



More From » xml

 Answers
41

Legacy Code


document.implementation.createDocument does not work on Chrome and Safari.


Use XMLHttpRequest instead when possible:


function loadXMLSync(url) {
try {
// Prefer XMLHttpRequest when available
var xhr = new XMLHttpRequest()
xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()

return xhr.responseXML
}
catch (e) {
// XMLHttpRequest not available, fallback on ActiveXObject
try {
var activex = new ActiveXObject('Microsoft.XMLDOM')
activex.async = false
activex.load(url)

return activex
}
catch (e) {
// Neither XMLHttpRequest or ActiveXObject are available
return undefined
}
}
}



Modern Browsers


If you're targeting modern browsers (> IE6), just use XMLHttpRequest:


function loadXMLSync(url) {
var xhr = new XMLHttpRequest()

xhr.open('GET', url, false)
xhr.setRequestHeader('Content-Type', 'text/xml')
xhr.send()

return xhr.responseXML
}

[#76126] Saturday, August 24, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
everardo

Total Points: 406
Total Questions: 104
Total Answers: 92

Location: Albania
Member since Sun, Nov 22, 2020
4 Years ago
;