开发者

Tiny sample JQuery get fail?

开发者 https://www.devze.com 2023-02-18 21:01 出处:网络
some days are just like this. Ok, I\'m trying to fetch some text using ... well, anything that will work. I thought JQuery might be a good approach, but, for good measure, i\'ll try XMLHttpRequest, to

some days are just like this. Ok, I'm trying to fetch some text using ... well, anything that will work. I thought JQuery might be a good approach, but, for good measure, i'll try XMLHttpRequest, too. Totally silent failure from both. I guess I just don't understand even this tiniest, simplest case. Here it is

If I type the following into the address bar of just about any browser, I get some nice text in a window

http://www.gutenberg.org/files/11/11.txt

Now, I want to write a little html file, on my disk, to do the same thing. Here is my attempt; I've gone over every letter of this file again and 开发者_如何学编程again, and checked with several online documents for proper JQuery & XMLHttpRequest syntax, and I cannot see anything wrong at all. But neither approach does anything at all.

Any advice?

Alice?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>

<script>

  document.write('Alice?')
  $.get(
    'http://www.gutenberg.org/files/11/11.txt', 
    function(data) {
      document.write(data);
      alert('Load was performed.');
    });

</script>

<script type="text/javascript">
    (function GetURL()
    {
        document.write('Alice?');
        var request = new XMLHttpRequest();
        var url = 'http://www.gutenberg.org/files/11/11.txt';
        request.open('GET', url, false);
        request.send(null);
        document.write(request.responseText);
    })();
</script>


It's a Cross-Domain Access problem (violation of Same Origin Policy). Essentially JavaScript refuses to load stuff from other servers (in newer Browsers, IE6 happily loads everything from anyone).

There are some workarounds listed in this article (Server Side proxy, IFrame, Flash/Silverlight plugin, CORS, JSONP) and another idea is EasyXDM.


AJAX doesn't allow you to access files on a different domain. If, however, you saved the file to your hard drive in the same place as your HTML and then used 11.txt instead of the URL, it would work.

0

精彩评论

暂无评论...
验证码 换一张
取 消