从typescript调用webservice时出错

时间:2013-02-21 14:29:36

标签: javascript jquery ajax typescript

我有以下打字稿实现:

/// <reference path="jquery.d.ts" />
interface INotificationService {
    serviceUrl: string;
    getNotifications(onNotificationReceived: (notifications: string) => any): void;
}
module GRCcontrol.Messaging {
    export class Notifier implements INotificationService {
        private serviceUrl: string;
        constructor(serviceUrl: string) {
            this.serviceUrl = serviceUrl;
            jQuery.support.cors = true;
        }
        getNotifications(onNotificationReceived: (notifications: string) => any) {
            var that = this;
            $.getJSON(that.serviceUrl, {}, function (response) {
                alert(response);
            }).fail(function (err) {
                alert(err.statusText);
            });
        }
    }
}
$(document).ready(function () {
    var notifier = new GRCcontrol.Messaging.Notifier("http://clwebsvr01/wp7test/api/user/getemail/P6dNT1EFOKYPtHxdPWgng2lKyMg=");
    notifier.getNotifications(function (notifications) {
        alert(notifications);
    });
});

Javascript中的输出是:

var GRCcontrol;
(function (GRCcontrol) {
    (function (Messaging) {
        var Notifier = (function () {
            function Notifier(serviceUrl) {
                this.serviceUrl = serviceUrl;
                jQuery.support.cors = true;
            }
            Notifier.prototype.getNotifications = function (onNotificationReceived) {
                var that = this;
                $.getJSON(that.serviceUrl, {
                }, function (response) {
                    alert(response);
                }).fail(function (err) {
                    alert(err.statusText);
                });
            };
            return Notifier;
        })();
        Messaging.Notifier = Notifier;        
    })(GRCcontrol.Messaging || (GRCcontrol.Messaging = {}));
    var Messaging = GRCcontrol.Messaging;
})(GRCcontrol || (GRCcontrol = {}));
$(document).ready(function () {
    var notifier = new GRCcontrol.Messaging.Notifier("http://clwebsvr01/wp7test/api/user/getemail/P6dNT1EFOKYPtHxdPWgng2lKyMg=");
    notifier.getNotifications(function (notifications) {
        alert(notifications);
    });
});

问题是它一直进入fail方法并返回status = 0和statusText = error。 我用Fiddler查看调用是否完成,fiddler没有问题地收到响应。

我怎样才能使这个东西正常工作?

1 个答案:

答案 0 :(得分:2)

这似乎根本不是TypeScript问题,而是JavaScript / JQuery尝试启用cors启用ajax调用的问题。

有充分理由,cors不允许对所有跨域资源进行全面访问。有关详细信息,请参阅此SO问题和答案:Is it safe to use $.support.cors = true; in jQuery?