简体   繁体   English

是否可以在远程服务器上加载和解析文件?

[英]Is it possible to load and parse file on remote server?

Is it possible to download and parse a plain text file from different domain with JavaScript? 是否可以使用JavaScript下载和解析来自不同域的纯文本文件?

I've got this fiddle so far, but I'm stuck figuring out what I'm doing wrong. 到目前为止,我已经有了这个小提琴 ,但我一直在搞清楚我做错了什么。

Markup: 标记:

  <div id="clickme">Click me</div>
  <div id="result">Result: </div>

Code: 码:

$("#clickme").click(function() {
  /* ###################################
     NOTE: im on say example.com/test.html but trying
     NOTE: to access different_domain_sample.com
   */
  var req = new XMLHttpRequest();
  var sURL = "http://www.google.com/robots.txt";

  req.open("GET", sURL, true);
  req.setRequestHeader("User-Agent", "blah/4.2");

  req.onreadystatechange = function() {
    if (req.readyState == 4) {
        $("#result").text("Result is: <pre>" + req.responseText + "</pre>");
    }
  };
  req.send(null);
});

Already answered, but more info on this is here Cross-origin resource sharing 已经回答了,但有关这方面的更多信息,请访问跨域资源共享

It's because of browsers have implemented a feature called cross-site-scripting-prevention. 这是因为浏览器实现了一种称为跨站点脚本防范的功能。 You could for example do the ajax request on a php file on the same server and in that query the target page using curl. 例如,您可以在同一服务器上的php文件上执行ajax请求,并使用curl在该查询中执行目标页面。

There are three ways to do this: 有三种方法可以做到这一点:

  1. With the help of a non-browser-based proxy served from your domain which will fetch the data on your behalf. 在您的域中提供的非基于浏览器的代理的帮助下,代理您将获取数据。 You can also use a plugin which can bypass the same-origin policy. 您还可以使用可以绕过同源策略的插件。
  2. Use JSONP or another similarly hackish way around the same-origin policy. 在同源策略中使用JSONP或其他类似的hackish方式。 This would require the web server to support JSONP. 这将要求Web服务器支持JSONP。
  3. Disable the cross-origin policy ( definitely not recommended ; very dangerous ) 禁用跨源策略( 绝对不推荐 ; 非常危险

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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