Techblog

Tech Blog

Our latest geek adventures!

Posts Tagged ‘json’

5 December Crossdomain JSON troubles: JSONCrossdomainRequest

Posted by jaap in Javascript

This week I was doing some work on a crossdomain JSON request. This was a pitty, because I had in mind, Ajax requests could be made between subdomains, but that wasn’t the case, therefore I had to come up with a solution.

Solution 1: Server-side proxy
One option we had, was a server-side proxy, but I didn’t like this solution. If you are proxying your crossdomain request through a webserver that has to handle a lot of requests per second, these requests can block other requests, because proxying is always a slow process.

Solution 2: JSONP
Then there is the JSONP method, which includes a script on the fly in the browser and this script is then evaluated. The problem however with this approach is that your JSON resources have to be rewritten as a evaluation. This evaluation is then executed and your JSON loaded in a variable.

Instead of:

{"somejsonobject":1}

you have to write:

var jsonobject = {"somejsonobject":1};
someCallback(jsonobject);

This is not very clean, because you have to decide in your remote JSON file what the variable will be named. JSONP is a method in which you give a variable and callback in the url and then the JSON will be rewritten. This solution is just not the right way, as we programmers all know why it is better to isolate logic from real data.

Solution 3: Crossdomain through flash
Then I looked at another solution that does crossdomain Ajax requests through a flash proxy. These solutions all gave a lot of problems, cause the encoding of characters was not handled properly by the Flash ExternalInterface compononent, which sended the JSON string it received to Javascript.

Solution 4: Parsing the JSON by flash
I then tried to make a solution myself that doesn’t send JSON string to Javascript, but (thanks for the idea Gert-Jan) sends the objects to Javascript. So the JSON is parsed into an object at the Actionscript side and it now all works. The project is opensourced under a MIT license and called: JSONCrossdomainRequest. It is a js file which includes a swf file in your page that can handle the requests. Please come over to GitHub and read more about how to install and use this project. The Actionscript project is also included. Good luck if you are going to use it and if you have any modifications let me know, it is a work in progress and we appreciate any help!

Project location:
http://github.com/japetheape/jsoncrossdomainrequest/tree/master

5 Comments - Tags: , , ,