开发者

jQuery Mobile App + remote REST Webservice: Alternatives to JSONP?

Currently I'm working on a jQuery Mobile website which will later be transformed into an app via Titanium. I have created a RESTful JSON web service, which is running on a different server than the jQuery Mobile application. The web service is consumed via AJAX using JSONP.

One thing I find annoying is that I can't make use of HTTP error codes, because jQuery automatically aborts a JSONP call whenever the server issues an error. I can never get hold of the error code on the client side.

Another thing is that JSONP only works with the HTTP verb GET, you cannot issue a JSONP POST for example (Currently, the web service is GET only, but that could change).

Are there any alternatives to JSONP? Or is JSONP the only choice I have when using remote JSON web services with AJAX? For example, how do Twitter apps interact with the Twitter API (t开发者_StackOverflowhey have a REST API)?


Your question is a nice illustration why people complain that jquery is too easy to adopt ;)

JSONP is not ajax. There are no success and failure callbacks. JSONP is this:

  1. put the parameters in the url
  2. add &jsoncallback=random2745273
  3. create a global variable random2745273 and put the callback reference in it
  4. add <script src="theurlhere"></script> to the head
  5. that's all you can do.

The server returns

random2745273({somedata});

and that's how your callback is called.

If you want to report errors, then your server has to generate a correct code. You will not know what HTTP headers were sent.

And this is the only way you can communicate cross-domain with an api. Sending cross-domain communicates is also possible with generating iframes, but it's hacky and rarely used.

[edit]

Ok, that got me thinking... I could use the iframe hack to wrap over the JSONP!

And as usual - I wasn't the first to have the idea (and I'm finally humble enough to google my ideas expecting it ;) )

Here it is: http://beebole.com/en/blog/general/sandbox-your-cross-domain-jsonp-to-improve-mashup-security/

awesome

[edit2]

awww, I forgot... There's another one.

window.postMessage

It already got implemented in some browsers. If you don't have to be compatible with most of the browsers, you can start using it now! :)


After some more research on postMessage I found an alternative to JSONP: AJAX via Cross-domain messaging with EasyXDM.

See http://easyxdm.net/wp/2010/03/17/cross-domain-ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜