Where the class TW3HttpRequest is more akin to an ordinary http client component under delphi or freepascal, it does come with some limitations. First and foremost the same origin policy and also the fact that it only deals with raw, unformatted data.
The alternative is the TW3JSONP class which is stored in SmartCL.Net.Http unit. It is very important to understand that these two classes utilize wildly different web technologies, and you simply cant switch one for the other. At least not without some control over the responding server.
Where TW3HttpRequest issues a raw http get or post command to your server (or a server that allow cross domain communication), TW3JSONP is all about webservices. So it expects the URL to be a program that executes on the server – and returns data in a very special way: namely as an executable script.
- Create a new script tag via code
- Point the source for the script tag to the JSONP webservice
- Add parameter to the source URL, telling the server what procedure to call
If that sounds very dangerous then yes, we agree, you should never call a webservice you do not trust, quite simply because you have no control over what the script you get back contains.
How to use it
The class that ships with smart is very easy to use. All in all you have to do only 3 things:
- write an event handler that will recieve the data
- call the Request method or set the url property
- process the data returned
The above example uses a relatively new pascal feature called anonymous procedures, so it might look a bit alien if you are used to classical event handlers, but at least it shows you how one could go about using it. The procedure above is an event handler for a button click, so add a button to a form and connect the HandleClick to the onClick event.
Processing the data
Now that we know how the data inside the variant we got back from the server is organized, extracting the values is easy enough. Drop a memo component on your form and alter the JSONP event handler to:
And voila – run the test again, click the button, and your memo now contains the headline of the first story: