Frage

I was wondering if somebody could help me with this, I've seen a few examples using the XDomainRequest on the web, but they don't really explain the code that well. I am trying to load an XML file, so I can parse it. The code I am using is below.

    var xdr = new XDomainRequest();             
           xdr.onerror = 
           function () 
           {
                    alert('Error!');
           };               
           xdr.ontimeout = 
           function () 
           {
                    alert('Timeout!');
           };

           xdr.onprogress = 
           function () 
           {
                    alert('Loading...');
           };
           xdr.onload = 
           function() 
           {
                    alert('File:' + xdr.responseText);
           }

           xdr.timeout = 10000;
           xdr.open("GET","http://www.spectraltechnologies.co.uk/webbuilder2020/Instrument_Lamps_New.txt", false);
           xdr.send();

Everytime I try and use this it always returns xdr.onerror and the accompanying alert. The file it requests was originally an XML file and is in XML format inside but I have made a .txt copy, as I understand this is the only thing XDomainRequest accepts.

I have been able to make a solution for Firefox and Chrome browsers, but Internet Explorer has caused me many problems. I really hope someone can help, thanks in advance.

War es hilfreich?

Lösung

I worked this out by persisting through the long and very specific specification of the XDomainRequest. My first issue was that the response header from the file/site, I was accessing was incorrect.

This site used a ".htaccess" file, so I was able to fix this issue by adding the below code:

    <filesMatch "\Instrument_Lamps_New.txt$">
    <IfModule mod_headers.c>
    Header add Access-Control-Allow-Origin "*"
    </IfModule>
    </filesMatch>

This code checks if the file being accessed, is the one I want the specified header for and then adds that to the header.

My second issue is that using XDomainRequest, you can only access files with the same protocol as the file you are opening the request from. i.e. http only opens http, https only opens https. Due to debugging the site, I was opening the page from my own file system, so the error occurred due to "file://..." ≠ "http://...".

So after making sure my response header included the "Access-Control-Allow-Origin" header and I uploaded the page it worked fine.

This site includes more information on XDomainRequest: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top