1

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.

Community
  • 1
  • 1
NcAdams
  • 2,521
  • 4
  • 21
  • 32
  • Plenty of free solutions to host your website, try https://c9.io/ – mccainz Jul 03 '14 at 17:20
  • 1
    How are you accesing the page? Are you also accessing it through the local server or just double clicking the file? – Hanlet Escaño Jul 03 '14 at 17:20
  • You can't use AJAX unless you are running your page off of a webserver. You can't just open the HTML file off your computer. You need to set up a (development) webserver. – gen_Eric Jul 03 '14 at 17:20
  • 2
    @HanletEscaño Oh man, should have thought about that. I was accessing it through the file:// protocol; when I tried http://localhost, it worked. Thanks! :D – NcAdams Jul 03 '14 at 17:24
  • @RocketHazmat That's the first time I've heard the term development webserver. I'll look it up, thanks! – NcAdams Jul 03 '14 at 17:35

1 Answers1

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.

Mark Su
  • 39
  • 1