简体   繁体   English

在本地文件上使用jQuery的“加载”方法

[英]Using jQuery's “load” method on a local file

I'm trying to create a website where each of several pages has the same title bar -- a pretty standard problem. 我正在尝试创建一个网站,其中每个页面的每个页面都有相同的标题栏-一个非常标准的问题。 To load the title bar's HTML, I use jQuery's "load" method: 要加载标题栏的HTML,我使用jQuery的“ load”方法:

$("#title-bar").load("path/to/titlebar-code.html")

However, it's become apparent that "load" really really does not like to load files from the local file system. 但是,很明显,“加载” 实际上并不真正喜欢从本地文件系统加载文件。 I don't have access to a remote server, so this is a problem. 我无权访问远程服务器,因此这是一个问题。 (I'm relying on my college to host the website, and they have not set up the server yet.) So I have no way to view or test the site until I resolve this. (我依靠我的大学托管该网站,并且他们还没有设置服务器。)因此,在解决此问题之前,我无法查看或测试该网站。

Attempted solution: I tried to run a local server with Node.js, using the code I found here , to trick jQuery into making the request. 尝试的解决方案:我尝试使用此处找到的代码通过Node.js运行本地服务器,以诱使jQuery发出请求。 Here is the server code: 这是服务器代码:

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(8080);

And the new jQuery request: 以及新的jQuery请求:

$("#title-bar").load("http://localhost:8080/path/to/titlebar-code.html")

... which returns the error: ...返回错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin 'null' is therefore not allowed access. 因此,不允许访问原始“空”。

I have limited web experience and I'm not sure how to proceed. 我的网络经验有限,我不确定如何继续。 Does anyone know a way to load a file like this? 有谁知道加载这种文件的方法? (Completely different solutions are welcome; Node and jQuery just seemed like promising ways to proceed) (欢迎使用完全不同的解决方案; Node和jQuery似乎是很有前途的方法)


SOLVED 解决了

Based on Hanlet's comment below, I accessed the website from http://localhost:8080 instead of file://path/to/website as I had been doing. 根据Hanlet在下面的评论,我从http://localhost:8080访问该网站,而不是像过去那样从file://path/to/website I then ran the load(http://localhost...) command from above. 然后,我从上面运行了load(http://localhost...)命令。 Worked with no problems. 工作没有问题。

Jquery ajax is limited to the same domain policy, local file or localhost file, as long as it is not the same domain as your script's hosting domain, it will not work. jQuery ajax限于相同的域策略,本地文件或localhost文件,只要它与脚本的托管域不是同一域,就无法使用。

You need to enable the CORS (Cross-Origin Resource Sharing) on the remote server you are loading the file from. 您需要在从中加载文件的远程服务器上启用CORS(跨域资源共享)。

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

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