2

我有以下打字稿实现:

/// <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收到响应没有问题。

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

4

1 回答 1

2

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

有充分的理由,cors不允许全面访问所有跨域资源。有关更多详细信息,请参阅此 SO 问题和答案:使用 $.support.cors = true 是否安全;在 jQuery 中?

于 2013-02-22T08:14:14.260 回答