Good afternoon, dear habriledi and habraJemplemeny. Today I will tell you about creating an API for your site. I know, the topic in some of its parts is quite sucked, but I came across a lack of certain information when developing an API for one of the projects.
It's about JSONP, SMD and the Dojo component dojox.rpc.Service.
Interesting? - I ask under the cat.
Let's start from the stove.
JSONP (JSON Padding) or “JSON with padding” is an extension of JSON when the name of the callback function is specified as an input argument to
WikipediaThe trick is that as a result, the server returns the javascript code for calling this function itself and passing the data to it. Thus, having connected this code on client side, we can bypass the
same origin restriction for normal Ajax-interaction.
SMD . SMD (service message description) is a JSON based description language for web services and access to them.
I will give an example of a simple smd file:
{ transport: "JSONP", envelope: "URL", target: "http://mysite.org/api/find", parameters: [ { name: "appid", optional: false, "default": "client" } ], services: { service1: { target: "http://mysite.org/api/find_image", parameters: [ { name: "query", type: "string", optional: false, "default": "" }, { name: "max_height", type: "integer", optional: true }, ] }, service2: { target: "http://mysite.org/api/find_video", parameters: [ { name: "query", type: "string", optional: false, "default": "" } ] }, } }
')
As you can see, the smd-file can be divided into two parts - the default parameters and the block with the parameters of specific services.
I will not dwell on deciphering the names of all the parameters - they speak for themselves - I note only that within the dojox.rpc.Service component
the
transport parameter can be one of the following values:
POST, GET, JSONPenvelope parameter - one of:
URL, JSON, PATHNow about tasty, or how to make it work
var smd = new dojox.rpc.Service("/smd/api_1.smd"); var d = smd.service1({query:"image_001"}); d.addCallback(function(result) { alert("gotcha! " + result); });
smd.service1 ({query: "image_001"})This line will return us a deferred-object to which we can assign a callback function (or several).
Now we can access services by name, having a configuration file at our location.
Remarks:begin1. To use the JSONP transport, you need to connect the library
dojo.io.script2. The
dojox.rpc.Service component must be loaded before
dojo.io.script to avoid the “no match found” error.
3. The server should return the body of the script (without the pair
script tag) with a call to the function whose name is passed in the
callback parameter. To avoid errors, you should check the function to
undefined -
habrahabr.ru/post/62314end.Well, that's all, thank you for your attention. Comments, corrections are welcome, at the request of workers, the article may be supplemented (perhaps something and lost sight).