4

I want to have a static website uploaded on an external server that will try to get JSON data from localhost:3000 (a server program will already be running on the user's computer).

I'm trying to do this with jQuery like this:

$.getJSON("http://localhost:3000/page", function(data){
    // process data...
});

Why am I getting cross-origin policy errors and how can I stop them? I thought accessing JSON data was supposed to negate those cross-site errors?

UPDATE 1

I have just tried the JSONP with callback as suggested but here's a weird issue: If I add a script tag that points to the localhost:3000/page URL, the callback is loaded and the data is displayed properly when the page is done loading, but this is not what I am aiming for.

If I try the same thing using the $.getJSON method, I still get the same error as before:

XMLHttpRequest cannot load http://localhost:3000/page. Origin http://localhost is not allowed by Access-Control-Allow-Origin..

Emre Erkan
  • 8,433
  • 3
  • 48
  • 53
user1092719
  • 483
  • 1
  • 5
  • 17

1 Answers1

3

Interesting idea!

But localhost is a totally different domain from somewebsite.com. So the same origin policy applies. You need either:

  • JSONP Which means the server on localhost needs to support wrapping the JSON in a custom callback
  • CORS Which allows true cross domain ajax, but lots of extra header fuzting is required on both ends of the request.

JSONP is probably the easiest to pull off. From the docs for $.getJSON():

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

Your localhost server then simply needs to use that callback parameter that jQuery will pass in. Meaning that instead of simply rendering this:

<%= jsonString() %>

The local server should render something more like this:

<% if (params.callback) { %>
  <%= params.callback %>(<%= jsonString %>);
<% } else { %>
  <%= jsonString %>
<% } %>
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
  • Thanks for your answer! I've just tried this but am still having trouble. Please see my updated question. – user1092719 Dec 11 '11 at 21:59
  • If you are getting that message, then jQuery are not using JSONP. Try the `$.ajax()` method with `dataType: "jsonp"` instead of `$.getJSON()`. When doing anything tricky the flexibility of the `$.ajax()` method is usually very recommended. – Alex Wayne Dec 11 '11 at 22:13
  • Aha! Now the data's loading fine, now I just gotta figure out how to make the callback fit in as much as possible. Thanks again, very helpful! :) – user1092719 Dec 11 '11 at 22:29
  • Please accept my answer by hitting the little checkmark at the top left of my post if my answer solved your problem :) – Alex Wayne Dec 11 '11 at 22:35