Read XML file using JavaScript in Chrome -
i need load , read xml file using javascript.
the following code works fine in firefox, ie , 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 code in chrome gives me error:
object# has no method "load"
legacy code
document.implementation.createdocument
not work on chrome , 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 xmlhttp.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 available return undefined } } }
modern browsers
if you're targeting modern browsers (> ie6), 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 }
Comments
Post a Comment