How to Create Cross Domain Javascript API

I need to create a simple Javascript cross domain API so that I can share data across a few web sites, and also allow other websites to consume my data through Javascrript API.

The following article is a good start point:  Javascript: Cross-Domain API For Your Website, or Javascript cross-domain api for your website

An example of Cross Domain Javascript API is disqus, other than many successful Google Javascript API.

The complete disqus javascript API can be found from this page:   disqus embed.js. It provides good example of how to handle different browser and perform cross domain call.

Note: In Asp.net, you can allow cross domain call by using following:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

Or you can set the cross-origin resource sharing in web.config file as indicated in article  cross-origin resource sharing


How ever, IE doe not support COSR accroding to the discussion, therefore, Proxy service is required. Check here: JavaScript: Use a Web Proxy for Cross-Domain XMLHttpRequest Calls.

Another good article to read before moving forward is JSON and JSONP by Angus Croll.

You can create a JSON web service in ASP.Net following the instruction of this article: How To Create A JSON Web Service In ASP.NET. In codeproject there is also a complete sample about json: Prepare a JSON Web Service and access it with JQuery . The article CRUD operation using Web API in Asp.net Web form application provides a good example of using JSON in an asp.net web form application.

There is a complete sample of how to create JSONP web service in the article from code project:  Accessing Remote ASP.NET Web Services Using JSONP. After downloading and testing the sample, I found it is working properly. Thus you can use it as an start point. The only thing I found is that it does not work on IE 7 because JSON data type is not supported in any IE before version 8. And JAPI like disqus clearly states that IE 7 is not supported. Therefore it might be OK to leave IE7 out.

The following is a successful approach to create a jsonp webservice with asp.net 4 + IIS7.

1. Follow article How To Create A JSON Web Service In ASP.NET to create a simple JSON web service first. This sample works well as a  same domain JSON webservice.

2. In order to make it a cross domain web service, chang the web.config file first so that it is possible to access the service from any file.

3. After above change you will be able to view the response of the web service by typing in following address:
http://localhost:58188/WebService.asmx/GetBooksByAuthor?strAuthor=1&jsonp=JSONPCallback_0.

Unfortunately the response is still an xml file even though you set it as Json format. There are many people asking about the same issue. After try many different answers, I found the following one actually works:
ASP.NET AJAX returning XML when JSON specified

4. A valid jsonp response (such as response from twitter) is like following

JSONPCallback_2({"kind": "Listing", "data": {"modhash": "", "children": [{"kind": "t3", "data": {"domain": "i.imgur.com", "banned_by": null, "media_embed": {}, "subreddit": "aww", "selftext_html": null, "selftext": "", "likes": null, "link_flair_text": null, "id": "13g6sy", "clicked": false, "title": "My pup loves to be tucked in", "num_comments": 104, "score": 2450, "approved_by": null, "over_18": false, "hidden": false, "thumbnail": "http://d.thumbs.redditmedia.com/kmvSp3tX_ixG2ipi.jpg", "subreddit_id": "t5_2qh1o", "edited": false, "link_flair_css_class": null, "author_flair_css_class": null, "downs": 3632, "saved": false, "is_self": false, "permalink": "/r/aww/comments/13g6sy/my_pup_loves_to_be_tucked_in/", "name": "t3_13g6sy", "created": 1353360833.0, "url": "http://i.imgur.com/yXjFf.jpg", "author_flair_text": null, "author": "r_i_l_e_y", "created_utc": 1353332033.0, "media": null, "num_reports": null, "ups": 6082}}], "after": "t3_13g6sy", "before": null}})

While the response from the service finished above is like this:
[["Book num0","book tile0","Author0"],["Book num1","book tile1","Author1"],["Book num2","book tile2","Author2"]]

Therefore, we need to continue to improve our way to send response back to the caller. Actually the only thing we need to do now is to detect whether the parameter "callback" is avaialbe or not, like following

String jsonString = "{success: true}";
String cb = Request.Params.Get("callback");
String responseString = "";
if (!String.IsNullOrEmpty(cb)) {
    responseString = cb + "(" + jsonString + ")";
} else {
    responseString = jsonString;
}
Response.Write(responseString);


After above change, our web service is a valid jsonp web service that can be consumed the same way as described in article  JSON and JSONP by Angus Croll.




Comments

  1. Is it really necessary to have a cross domain? Will it attract many customers to visit your site? Will it increase the traffic of your site?
    I just have to know some advantages of it.

    domains

    ReplyDelete
  2. Actually across domain is widely used. Most commonly used one is google analitics, google adsense, google Maps. I guess there must be some advantages. As to me, I just want to use one website to provide data/feature to multiple websites. I figure that the approach that disqus used can provide what I need. Maybe there are some other easy ways to do it?

    ReplyDelete
  3. Yeah Actually across sector is normally used. Normally used one is search engines analitics, google adsense, search engines Charts. I think there must be some benefits. As to me, I just want to use one website to offer data/feature to several websites.

    ReplyDelete

Post a Comment

Popular posts from this blog

Javascript Hosted on Google Drive Not Working Reliably

Newsmag Theme and External Featured Image

Responsive Web Design