Search code examples
ajaxwindows-8winjswindows-store

Winjs get request failing to return data


I encountered a strange problem. In my app I have the following code

WinJS.xhr({
                url: 'http://bdzservice.apphb.com/api/Route?fromStation=София&toStation=Варна&date=30/08/2013&startTime=00:00&endTime=24:00'

            }).then(function (success)
            {
                console.log(success);
            },
            function (error)
            {
                console.log(error);
            }
            );

The problem is I get an empty response text (with status 200). The Url I provided returns data through the browser and other rest clients, but in the app I get no data. Where might be the problem?


Solution

  • You need to encode query string parameters via encodeURIComponent (browser does this for you automatically when pasting url).

    Following code will do the trick:

    function serialize (obj) {
    var str = [];
    for (var p in obj) {
        if (obj.hasOwnProperty(p)) {
             str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
         }
     }
    
     return str.join("&");
    };
    
    var request = {
        fromStation: 'София',
        toStation: 'Варна',
        date: '30/08/2013',
        startTime: '00:00',
        endTime: '24:00'
    };
    WinJS.xhr({
        url: 'http://bdzservice.apphb.com/api/Route?' + serialize(request)
    }).then(function(success) {
        console.log(success);
    },
        function(error) {
            console.log(error);
        }
    );