How to create a mashup using WinJS.xhr (HTML)

[ This article is for Windows 8.x and Windows Phone 8.x developers writing Windows Runtime apps. If you’re developing for Windows 10, see the latest documentation ]

A mashup is a web application that uses data from two or more sources to create something new. This example shows you how to use XMLHttpRequest (XHR) to retrieve and display a remote Really Simple Syndication (RSS) feed.

What you need to know

Technologies

Prerequisites

Instructions

Step 1: Set up your app for accessing the web

Apps need to add certain capabilities explicitly, such as accessing the network. For more information about capabilities, see App capability declarations and How to configure network capabilities.

  1. In Visual Studio, create a blank JavaScript app.

  2. Open the package.appxmanifest file and go to the Capabilities tab.

  3. For the Windows version of the sample, the Internet (Client) capability should already be selected, but if not select it now. If the app might need to connect as a client to web services on a home network or work network, then the Private Networks (Client & Server) capability is also needed.

    For the Windows Phone version of the sample, select the Internet (Client & Server) capability.

    Note  On Windows Phone, there is only one network capability (Internet (Client & Server) which enables all network access for the app.

     

Step 2: Obtain an RSS feed

The WinJS.xhr function uses XHR to retrieve data from a specified URL. The WinJS.xhr is asynchronous and returns a Promise for the requested data. To obtain the RSS feed, you specify a fulfilled handler for this Promise. (You can also specify an error handler and a progress handler.)

You can call the WinJS.xhr function from any page in your package (any page in the local context).

Note  Note: The target URL for an XHR request is not restricted by the app's ApplicationContentUriRules (which are listed in the app's package manifest).

 

This example uses WinJS.xhr to access the rss.msnbc.msn.com RSS feed. It passes two callback functions to the Promise:

  • xhrParseXml: The fulfilled handler. This function is called if the XHR request was successful.
  • xhrError: The error handler. This function is called if the request was not successful.
WinJS.xhr({ url: "http://rss.msnbc.msn.com/id/3032127/device/rss/rss.xml" }).then(
    xhrParseXml, xhrError
    );

You'll define the xhrParseXml and xhrError methods in the next step.

Step 3: Parse the results

If the WinJS.xhr request is successful, the code in the last example calls the xhrParseXml. The xhrParseXml function iterates through the RSS items and generates a link to each one. It displays the link in a div on the main page, xhrOutput.

function xhrParseXml(result) {

    var outputArea = document.getElementById("xhrOutput");
    var xml = result.responseXML;


    if (xml) {
        var items = xml.querySelectorAll("rss > channel > item");
        if (items) {
            var length = Math.min(10, items.length);
            for (var i = 0; i < length; i++) {
                var link = document.createElement("a");
                var newLine = document.createElement("br")
                link.setAttribute("href", items[i].querySelector("link").textContent);
                link.innerText = (i + 1) + ") " + items[i].querySelector("title").textContent;
                outputArea.appendChild(link);
                outputArea.appendChild(newLine);
            }
        } else {
            outputArea.innerHTML = "There are no items available at this time";
        }
    } else {
        outputArea.innerHTML = 
            "Unable to retrieve data at this time. Status code: " + statusCode;
    }
}

The next example shows the HTML declaration for the output area.

<div id="xhrOutput">
</div>

Step 4: Handle errors

There's always a chance that you won't be able to access the remote data, so provide a way to handle errors processing your XHR request. This example defines a simple error handler.

For more information, see Handling exceptions in network apps.

function xhrError(result) {

    var statusCode = result.status; 
    var outputArea = document.getElementById("xhrOutput");
    outputArea.innerHTML = 
        "Unable to retrieve data at this time. Status code: " + statusCode;
}

Complete example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Mashup</title>

    <!-- WinJS references - Windows -->
    <link href="//Microsoft.WinJS.2.0/css/ui-dark.css" rel="stylesheet">
    <script src="//Microsoft.WinJS.2.0/js/base.js"></script>
    <script src="//Microsoft.WinJS.2.0/js/ui.js"></script>

    <!-- WinJS references - Phone -->
    <link href="/css/ui-themed.css" rel="stylesheet" />
    <script src="//Microsoft.Phone.WinJS.2.1/js/base.js"></script>
    <script src="//Microsoft.Phone.WinJS.2.1/js/ui.js"></script>

    <!-- Mashup references -->
    <link href="/css/default.css" rel="stylesheet">
    <script src="/js/default.js"></script>
</head>
<body>

    <div id="xhrOutput">
    </div>
</body>
</html>

// default.js
(function () {
    "use strict";

    var app = WinJS.Application;

    // This function responds to all application activations.
    app.onactivated = function (eventObject) {
        if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
            // Initialize your application here.
            WinJS.UI.processAll();
            loadRemoteXhr();
        }
    };

    function loadRemoteXhr() {

        document.getElementById("xhrOutput").innerHTML = "";
        WinJS.xhr({ url: "http://rss.msnbc.msn.com/id/3032127/device/rss/rss.xml" }).then(
            xhrParseXml, xhrError
            );

    }

    function xhrParseXml(result) {

        var outputArea = document.getElementById("xhrOutput");
        var xml = result.responseXML;

        if (xml) {
            var items = xml.querySelectorAll("rss > channel > item");
            if (items) {
                var length = Math.min(10, items.length);
                for (var i = 0; i < length; i++) {
                    var link = document.createElement("a");
                    var newLine = document.createElement("br")
                    link.setAttribute("href", items[i].querySelector("link").textContent);
                    link.innerText = (i + 1) + ") " + items[i].querySelector("title").textContent;
                    outputArea.appendChild(link);
                    outputArea.appendChild(newLine);
                }
            } else {
                outputArea.innerHTML = "There are no items available at this time";
            }
        } else {
            outputArea.innerHTML = 
                "Unable to retrieve data at this time. Status code: " + statusCode;
        }
    }

    function xhrError(result) {

        var statusCode = result.status;
        var outputArea = document.getElementById("xhrOutput");
        outputArea.innerHTML = "Unable to retrieve data at this time. Status code: " + statusCode;
    }


    app.start();
})();

For a downloadable sample that contains more features, see the Integrating content and controls from web services sample.

Other resources

Connecting to web services

Handling exceptions in network apps

How to download a file with WinJS xhr

Reference

WinJS.xhr

XMLHttpRequest

XMLHttpRequest enhancements

Samples

Integrating content and controls from web services sample

Using a Blob to save and load content sample

Web authentication sample

XHR, handling navigation errors, and URL schemes sample