-1

I am trying to retrieve JSON Data from the tumblr-API.

No problems when using jQuery

$.getJSON("http://api.tumblr.com/v2/blog/blog.com/posts?api_key=key&jsonp=?", function(data) {
    console.log(data);
});

But trying to get the data with an XMLHttpRequest, i get the

XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost' is therefore not allowed access.

error msg.

    var url = "http://api.tumblr.com/v2/blog/blog.com/posts?api_key=key";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "json";
    xhr.onload = function () {
        console.log(xhr.response);
    };


xhr.send();

I really want to get the data without jQuery. So what does jQuery that i am not doing? Thank you very much.

1 Answers1

0

By inserting a ? in the URL, you are making jQuery issue a request using the JSONP technique instead of XMLHttpRequest.

To do this:

  1. Assign your load handler function to a global variable. You should generate a unique name for this. (e.g. var f_name = "jsonp" + ++unique_function_count; window[f_name] = function () { ... }).
  2. Replace the question mark in your URI with the function name
  3. Create a script element var script = document.createElement('script');
  4. Set the URI as the source of the script (script.src = uri;)
  5. Load the script (document.body.appendChild(script);)
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335