Get JSON from subdomains with jQuery -
i have user1.mydomain.com
, user2.mydomain.com
domains. use api.mydomain.com
deal web app on ajax/json. so, want make post request user1.mydomain.com
api.mydomain.com/projects
using jquery this: {'action':'getactiveprojects'}
list of active projects user1 in json result. found $.getjson
method seems there no option sending data server, method. other problem face same origin policy. so, how can post json server on subdomain , json response result?
using $.ajax
, json-p specifying datatype: "jsonp"
. details in linked docs. server have respond json-p rather json, that's pretty easy if control server.
alternately, if need support recent browsers (and not ie), can set server support cors. that's supported in recent browsers, , although ie8 supports it, doesn't support transparently through usual xmlhttprequest
object, instead requires different transport object (xdomainrequest
), jquery doesn't handle automatically (yet).
here's json-p example using jquery:
$.ajax({ // source url url: "http://jsbin.com/ubucu4", // tell jquery you're doing json-p datatype: "jsonp", // include data request if like; // example doesn't *use* data data: {some: "data"}, // can control name of callback, // don't want , jquery handle // you. have here because i'm doing // example on jsbin. jsonpcallback: "examplecallback", // success callback success: function(data) { display("received data, typeof data = " + typeof data); display("data.foo = " + data.foo); display("data.bar = " + data.bar); }, // error callback error: function(jxhr, status, err) { display("error, status = " + status + ", err = " + err); } });
on server, you'll see jquery has added callback
parameter url, e.g. in above http://jsbin.com/ubucu4?callback=examplecallback
if jquery control name bit more exotic. server-side code should construct response javascript function call, calling function. response in above example is:
examplecallback({ "foo": "this foo", "bar": "this bar" });
this happens because instead of using xmlhttprequest
, subject same origin policy, json-p uses dynamically-added script
tag (which fine). in example, tag like
<script type='text/javascript' src='http://jsbin.com/ubucu4?callback=examplecallback'></script>
the browser retrieve script, json-p response, , execute it. means callback gets called, , data supplied script.
your json-p response isn't, technically, json; it's javascript, , reasons it's essential use json-p servers trust (such own subdomain servers), since you're injecting code directly page. otherwise, if you're using server can't trust, code gets injected may read information off page , send third party. let caution watchword.
Comments
Post a Comment