ค้นหาเว็บไซต์

javascript - เกิดข้อผิดพลาดเมื่อเรียกใช้งานเว็บเซอร์วิสจาก 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

นี่ดูเหมือนไม่ใช่ปัญหาของ TypeScript เลย แต่เป็นปัญหากับความพยายามของ JavaScript/JQuery ในการทำการเรียก ajax ที่เปิดใช้งาน cors

ด้วยเหตุผลที่ดี, cors ไม่อนุญาตการเข้าถึงทรัพยากรข้ามโดเมนทั้งหมดโดยตรง ดูคำถามและคำตอบใน SO นี้เพื่อรายละเอียดเพิ่มเติม: การใช้ $.support.cors=true; ใน jQuery ปลอดภัยหรือไม่?