[SalesForce] AJAX load JSON from static resource

I am trying to load a JSON file into my VF app via AJAX. It currently sits in a zipped static resource, like such:

myResources
          |
          |js
            |
            |target.json
            |scripts.js

I am able to call scripts.json by using the following:

I am trying an ajax call like this (from the vf page):

var sfJSON;
var jsonURL = "{!URLFOR($Resource.myResources, 'myResources/js/target.json')}";

$j.getJSON(jsonURL, function(data){
        sfJSON = data;
});

However this isn't working. No error is occurring – jQuery mentions that this will fail silently.

When I look at the source in chrome inspector, I see that the VF page has correctly changed the URL to

"/resource/000000/myResource/myResource/js/target.json"

(the double myResource is accurate).

When I try just navigating to that url, I do get the json file. But for some reason, it isn't loading via the AJAX call.

What am I missing?

Thank you!

Best Answer

I've actually kind of figured it out. There is some issue with my use of $.getJSON, however $.ajax works fine. I'll explore why .getJSON wasn't working.. Either way, I've moved my code back into the JS file and only kept the URLFOR exposed in the VF page to get the actual URL.

Yep, this resource is nailed by a cross-origin restriction.

Inspecting the Network tab will show if the request is aborted.

When you load things with a relative URL, jQuery doesn't actually know where the final endpoint will live. The response may redirect jQuery off your current domain to (eg) the Visualforce content domain. But it must choose a request strategy (same-domain / cross-domain) at the time you call the function.

The ultimate same-domain or a cross-domain nature of the request is not known until the response comes back ;-) the difference between $.getJson and $.ajax is that one of them may not handle the redirect well with the default options.

Related Topic