Jquery Ajax - Tumblr API v2

跟風遠走 提交于 2019-12-06 03:25:54

Do what Tumblr is telling you to - add a callback function name to the request

myJsonpCallback = function(data)
{
    console.log(data);
}

$.ajax({
    type: "GET",
    url : "http://api.tumblr.com/v2/blog/MyTumblrName.tumblr.com/info",
    dataType: "jsonp",
    data: {
        api_key : "MyTumblrApi",
        jsonp : "myJsonpCallback"
    }
});

========================================================

EDIT: The console.log thing is a syntax error since I didn't actually test this code.

What happens to success? I don't really know. Try and find out :) It will probably be called but data parameter likely be null or something. The issue here is that jQuery names it's callback parameter callback, where as Tumblr is expecting jsonp. Upon 200 response jQuery likely simply eval()s the response, which is why myJsonpCallback is actually called.

Stepan Vrany

In case you don't want to use jQuery:

var tumblrFeed = document.createElement('script');
tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/{blog.tumblr.com}/posts?api_key={your api key}&jsonp=callback");
document.getElementsByTagName("head")[0].appendChild(tumblrFeed)

function callback(data){
  console.log(data);
}

I've created simple function for this purpose:

function jsonpRequest(opt){
  var params = "";
  var blogName = "{your blog name}";
  var api_key = "{api key}";
  if("selector" in opt){params = "id=" + opt.selector;}
  if(("offset" in opt) && ("limit" in opt)){params = "limit=" + opt.limit + "&offset=" + opt.offset;}
  if("callback" in opt){params += "&jsonp=" + opt.callback;}else{params += "&jsonp=callback";}
  params += "&api_key=" + api_key;      


  var tumblrFeed = document.createElement('script');
  tumblrFeed.setAttribute("src", "http://api.tumblr.com/v2/blog/" + blogName + "/posts?" + params);
  document.getElementsByTagName("head")[0].appendChild(tumblrFeed)
}

How to use it: jsonpRequest({offset: 50, limit: 5});

function callback(data){do stuff here ...}

Alternative usage: jsonpRequest({offset: 50, limit: 5, callback: "nameOfMyAmazingCallbackFunction"});

function nameOfMyAmazingCallbackFunction(data){do stuff here ...}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!