开发者

Best Practice for Handling AJAX requests from website to API provider

开发者 https://www.devze.com 2023-02-07 02:32 出处:网络
So, I implemented 开发者_运维技巧an API provider to be accessed by both web application and mobile applications.

So, I implemented 开发者_运维技巧an API provider to be accessed by both web application and mobile applications.

Most likely this will not be a large scale project, but I want to maximize my learning experience and geek out where I can.

Anyway, from what I understand, it seems like it's better to put the API provider service and the actual website on separate domains to make scaling easier. For example, twitter has the website twitter.com and api.twitter.com.

One immediate issue would be dealing with the cross-domain issue with AJAX. From what I gather, there are 2 ways to implement cross-domain AJAX

  1. JSONP: I heard about it, but don't know much beyond the name
  2. Proxy Server: so, my website is build on top of ASP.NET MVC and I was thinking about creating a APIProxy controller to handle all cross-domain API requests.

That way, I would make an AJAX call via $.ajax(settings) and then pass in the website URL that corresponds to the APIProxy controller. The APIProxy controller would then make the appropriate POST server calls and process the JSON responses and return the response back to AJAX callback functions.

I heard about flXHR about I don't want to use Flash because devices like the iPad or any a lot of mobile browsers don't support Flash.

Anyway, I just wanted to ask what are some of the best practices in managing a website with the API provider on a separate domain or subdomain.


When you request some JSON, it returns an object or array. Script tags are not subject to the same-domain rule. So instead making an AJAX call, you would essentially do this:

<script src="Http://api.example.com?param1=something&etc"></script>

That would load the JSON, and it would execute as JavaScript.

...But a simple object or array "executing" by itself isn't very useful. So when you request the JSON, you also include the name of a callback function. If the provider sees that a callback was provided, instead of just returning JSON, it actually returns JavaScript: the JSON is passed to your function as an argument.

Then, when the script loads, your function (which you already defined) is called, and given the JSON to work with.

That's JSONP.

Bibliography

  1. Newton, Aaron. "Request.JSONP." Clientcide. 7 Dec. 2009. Web. 28 Jan. 2011.
0

精彩评论

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

关注公众号