I have a working HTML5/JS app that I’m trying to port to the browser for a demo. The app was built to run in a vehicle and used the vehicle manufacturer’s network API for get/post requests.
For the browser version of this, I’m trying to use jQuery for get/post. However, I’m immediately running into issues.
XMLHttpRequest cannot load http://<API I AM CALLING>. Origin null is not allowed by Access-Control-Allow-Origin.
I’ve looked into the same origin policy, but still do not fully understand it. I can browse to the URL being used, and see the JSON I’m trying to retrieve.
Looking around the web, a lot of people suggested specifying JSONP as the dataType in my ajax call. I gave this a shot, with no success.
$.ajax({
url: url,
type: "GET",
dataType: "jsonp",
success: function (data, textStatus, jqXHR) {
log("success getting JSON from " + url);
success(data);
},
error: function (jqXHR, textStatus, errorThrown) {
log("error getting JSON from " + url + ", code " + JSON.stringify(jqXHR));
log("textStatus is " + textStatus);
log("errorThrown is " + errorThrown);
},
});
An error shows up in my console:
Uncaught SyntaxError: Unexpected token :
After that, my error callback is used.
error getting JSON from http://<API I AM CALLING>, code {"readyState":4,"status":200,"statusText":"success"}
textStatus is parsererror
errorThrown is Error: jQuery180006523256213404238_1346098086632 was not called
It looks like the server is responding with the JSON data I need. But, I’m guessing that jQuery is expecting this data to be wrapped in a function so it fails to parse it.
I have no control over the server whose API I am calling. Since the data is coming back to the browser, I feel like there’s got to be some way to access it.
Note:
App is only targeted for webkit browsers, I don’t need to support any others. Leaving dataType as “json” only causes problems in Chrome but Safari seems to work fine due to different security policies. Looking for a code workaround, not simply launching Chrome with special arguments. This still happens in Chrome even when I host my code on Apache, so it’s not just limited to me trying to open index.html locally.
One possible solution would be to write a service that proxies the JSON service you want and returns JSONP. I’ve written many proxy services like this so I can get around the same origin policy.
For instance: http://high-cloud-3702.heroku.com/
This service is a jsonp proxy for urban dictionary.
You can write a proxy like this in Sinatra very easily and host it on Heroku for free.
The key to a proxy like this is this code: