0

I'm just diving into JSON and found the following .json file from data.gov: http://data.consumerfinance.gov/api/views.json

Why don't I need the ?jsoncallback=? to retrieve the data?

(function() {
  $.getJSON('http://data.consumerfinance.gov/api/views.json', function (data) {
      console.log(data);
    });
})(); 

The posted code works. Is it because I use an anonymous callback function? Can I retrieve any .json file from any server or (what for) do I need an API?

2
  • jsonp request need callback.... normal json not Commented Sep 25, 2015 at 14:10
  • Some public APIs allow calls without the need for callback. Others for various reasons do not. Commented Sep 25, 2015 at 14:11

2 Answers 2

1

That code will attempt to use XMLHttpRequest to fetch the data.

By default, the Same Origin Policy will prevent JavaScript in a webpage from reading data across domains.

JSONP is a hack to work around the Same Origin Policy (it depends on the data being expressed in the form of a JavaScript program).

CORS was developed as a standard, and more nuanced, method to allow access to cross-origin resources.

data.consumerfinance.gov implements CORS.

This involves adding extra HTTP response headers which give explicit permission to the browser for it to share the data with JavaScript on other websites.

Sign up to request clarification or add additional context in comments.

Comments

1

That server sends Access-Control-Allow-Origin: * in the response, which tells your browser to ignore the Same-Origin Policy.

Therefore, you can do a normal AJAX request, without needing JSONP.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.