我有以下 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收到响应没有问题。
我怎样才能让这个东西正常工作?
最佳答案
这似乎根本不是 TypeScript 问题,而是 JavaScript/JQuery 尝试进行启用了 cors
的 ajax 调用的问题。
出于充分的理由,cors
不允许全面访问所有跨域资源。有关更多详细信息,请参阅此问题和答案:Is it safe to use $.support.cors = true; in jQuery?
关于javascript - 从 typescript 调用Web服务时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15004778/