Post JSON data to web services in Windows 8

Posted by on

Javascript

I have started working on a few metro style apps on Windows 8 using WinJS so I thought I might show some of my findings.

Using the WinJS.xhr function. (MSDN on WinJS.xhr)

Lets have a look at a basic basic example: (GET)

WinJS.xhr({ url: "http://example.com/api/test" });

This function takes an options object as a parameter. The url property is the only required option for this function, this sets the url for the request.

A more advanced example: (POST)

WinJS.xhr({
            type: "post",
            url: "http://example.com/api/test",
            headers: { "Content-type": "application/json" },
            data: JSON.stringify({ someProperty: "DK" })
        })
Looking at the example above we have set a few other options here:
  • type - this is the HTTP method used for the request (get, post, head, etc.)
  • data - this is the actual data I want to send through with the request
  • headers - this lets us set specific headers on the http request (NOTE: If your sending JSON make sure you set the content-type here!)

Now if we wanted to add handlers for success and error we can do this using the Promise.done method (MSDN on Promise.done)

WinJS.xhr({
            type: "post",
            url: "http://example.com/api/test",
            headers: { "Content-type": "application/json" },
            data: JSON.stringify({ someProperty: "DK" })
        }).done(onSuccess, onError, onProgress);
There you go, thats using WinJS to post JSON data to web services.