简体   繁体   中英

How do i use javascript to read a text file and display it on my website?

This is what i tried now:

<script>
function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}
</script>
<script>
readTextFile("http://newsxpressmedia.com/files/theme/test.txt");
</script>

But it's not working the page throw like meassage without a message error. Just popup a window since it's not working.

What i want to do on my site is to read the file content line by line an display it on my website.

The does exist on the link: http://newsxpressmedia.com/files/theme/test.txt

Is your site same as newsxpressmedia.com? If not it is a cross-domain issue. Browsers do not allow ajax calls to access different domain. More info .

This sounds like a same origin security issue . Without some special cross origin permissions from the target domain, the browser won't let you do ajax to a site that's at a different domain than your web page.

See MDN's page on the same-origin policy for details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript

See MDN's page on CORS for cross origin permissions: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS , but this requires cooperation from the target site.


The typical work-arounds are either to have your server work as a proxy so you can request the file from your server and your server gets the file from the actual web site or find a way to use an iframe in your web page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM