[cl-json-devel] jsonp
Henrik Hjelte
henrik at evahjelte.com
Wed Apr 13 15:05:25 UTC 2011
On Tue, Apr 12, 2011 at 11:28 PM, Haris <fbogdanovic at xnet.hr> wrote:
> Hi.
>
> Can someone give me an example of using jsonp ?
> For example, I have a lisp function:
> (defun add (x y)
> (+ x y))
> and I want to call it from javascript:
> add (2, 2);
> How do I do that ?
It depends on the web-server. Here are some steps:
1. You need to define a query parameter that specifies the name of the
callback javascript function. Popular choices are "callback" or
"jsoncallback"
2. You need to set the response-type to application/javascript since
it is not really json you return but a small javascript function call.
3. You need to get the x and y parameter, call add and generate a json-reponse.
If the actual example is the add function the json equivalent to 4 is
just 4 so you don't even need cl-json.
4. The json-reponse 4 should be made to look as a javascript function
call, wrapped in parenthesis, end with a semicolon and have the
callback function prepended.
If you call mywebserver?fn=add&x=2&y=2&callback=foo you should
generate this string as an answer: foo(4);
And again served as application/javascript.
For hunchentoot, an untested implementation, not optimized for
efficiency or safety:
(hunchentoot:define-easy-handler (jsonp-sample :uri "/add") (callback x y)
(setf (hunchentoot:content-type*) "application/javascript")
(let ((answer (+ x y)))
(format nil "~a(~a);"
callback
(json:encode-json-to-string answer))))
I would start to test with an even easier version, with "alert" as a
predefined callback and no x and y and no json-encode to see if you
get hunchentoot running and get a response that works, then take it
from there.
Hope it helps,
/Henrik
More information about the cl-json-devel
mailing list