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

邮差的信 提交于 2020-11-29 10:16:49

问题


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:

$("#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. 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:

$("#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. 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)


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. I then ran the load(http://localhost...) command from above. Worked with no problems.


回答1:


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.

You need to enable the CORS (Cross-Origin Resource Sharing) on the remote server you are loading the file from.



来源:https://stackoverflow.com/questions/24559763/using-jquerys-load-method-on-a-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!