다음을 통해 공유


Microsoft AJAX 라이브러리를 사용하여 사용자 지정 클라이언트 스크립트 만들기

업데이트: 2007년 11월

ASP.NET의 AJAX 기능은 클라이언트 스크립트를 만들어 ASP.NET 응용 프로그램에 통합하는 데 도움을 줍니다. 여기에는 ECMAScript(JavaScript)에 대한 형식 시스템과 기존 ECMAScript(JavaScript) 개체에 다양한 .NET Framework 클래스를 제공하는 이 개체에 대한 확장이 포함됩니다. 또한 ASP.NET에는 응용 프로그램에서 이러한 스크립트 라이브러리와 사용자 지정 스크립트를 관리하기 위한 ScriptManager 컨트롤이 포함되어 있습니다.

이 항목에는 다음과 같은 단원이 포함되어 있습니다.

  • 시나리오

  • 형식 시스템 사용

  • JavaScript 기본 형식에 대한 확장 사용

  • 클라이언트 스크립트를 ASP.NET 웹 응용 프로그램에 통합

시나리오

Microsoft AJAX 라이브러리의 기능은 다음과 같은 경우에 사용할 수 있습니다.

  • JavaScript 코드에 개체 지향 기능을 추가하여 코드 재사용, 유연성 및 관리 용이성을 높이려는 경우

  • 리플렉션을 사용하여 런타임에 클라이언트 스크립트의 구조 및 구성 요소를 검토하려는 경우

  • 열거형을 사용하여 정수 표현에 대해 쉽게 읽을 수 있는 대안을 제공하려는 경우

  • JavaScript 기본 형식에 대한 확장을 사용하여 일반적인 스크립팅 작업에 대한 개발 시간을 줄이려는 경우

  • 디버깅 확장 및 추적 기능을 사용하여 일반적인 JavaScript 디버깅 기법을 사용하는 경우보다 디버깅 속도와 정보의 양을 늘리려는 경우

형식 시스템 사용

Microsoft AJAX 라이브러리에서는 .NET Framework의 기능과 비슷한 자주 사용되는 개체 지향 기능을 제공하기 위해 JavaScript 개체에 대한 형식 시스템 및 확장을 추가합니다. 이러한 기능을 사용하면 유지 관리 편리성을 높이고, 기능 및 레이어 기능을 보다 쉽게 추가할 수 있도록 체계적으로 AJAX 사용 ASP.NET 응용 프로그램을 작성할 수 있습니다. Microsoft AJAX 라이브러리 확장은 JavaScript에 다음과 같은 기능을 추가합니다.

  • 클래스

  • 네임스페이스

  • 상속

  • 인터페이스

  • 열거형

  • 리플렉션

또한 라이브러리는 문자열 및 배열에 대한 도우미 함수를 제공합니다.

클래스, 멤버 및 네임스페이스

Microsoft AJAX 라이브러리에는 기본 클래스와 이러한 클래스에서 파생되는 개체 및 구성 요소가 포함되어 있습니다. 이러한 클래스를 사용하면 개체 지향 프로그래밍 모델을 통해 클라이언트 스크립트를 작성할 수 있습니다. 

Type 클래스는 네임스페이스, 클래스 및 JavaScript 프로그래밍에 대한 상속 같은 개체 지향 기능을 추가합니다. Type 클래스를 사용하여 등록되는 JavaScript 개체는 이 기능에 자동으로 액세스할 수 있습니다. 다음 예제에서는 Type 클래스를 사용하여 JavaScript 파일에서 네임스페이스와 클래스를 만들고 등록하는 방법을 보여 줍니다.

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
    this._firstName = firstName;
    this._lastName = lastName;
    this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

    getFirstName: function() {
        return this._firstName;
    },

    getLastName: function() {
        return this._lastName;
    },

    getName: function() {
        return this._firstName + ' ' + this._lastName;
    },

    dispose: function() {
        alert('bye ' + this.getName());
    }
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

클래스에는 필드, 속성, 메서드 및 이벤트라는 네 가지 유형의 멤버가 포함될 수 있습니다. 필드와 속성은 클래스 인스턴스의 특성을 설명하는 이름/값 쌍입니다. 필드는 다음 예제에서처럼 기본 형식으로 구성되어 있으며 직접 액세스할 수 있습니다.

myClassInstance.name="Fred"

속성은 기본 형식이나 참조 형식을 나타낼 수 있습니다. 속성 값에는 get 및 set 접근자 메서드를 사용하여 액세스합니다. Microsoft AJAX 라이브러리에서 get 및 set 접근자는 함수이며, 규칙에 따라 함수 이름에 접두사 "get_" 또는 "set_"을 사용합니다. 예를 들어 cancel과 같은 속성의 값을 가져오거나 설정하려면 get_cancel 또는 set_cancel 메서드를 호출합니다.

Microsoft AJAX 라이브러리에서는 AJAX 클라이언트 응용 프로그램의 수명 주기 동안 발생하는 작업에 대한 응답으로 이벤트를 발생시킵니다. 또한 Microsoft AJAX 라이브러리는 AJAX 클라이언트 구성 요소에 대한 사용자 지정 이벤트를 만들기 위한 표준 방식을 제공합니다. 자세한 내용은 사용자 지정 클라이언트 이벤트 만들기AJAX 클라이언트 수명 주기 이벤트를 참조하십시오.

Microsoft AJAX 라이브러리를 사용하면 공통 기능을 그룹화할 수 있도록 네임스페이스를 등록할 수 있습니다. 다음 예제에서는 Type.registerNamespaceregisterClass 메서드를 사용하여 Demo 네임스페이스에 Person 클래스를 추가하는 방법을 보여 줍니다.

ASP.NET 웹 페이지에 대해 AJAX 기능을 활성화하려면 ScriptManager 컨트롤을 페이지에 추가해야 합니다. 페이지가 렌더링되면 AJAX 클라이언트 스크립트 라이브러리에 대한 적절한 스크립트 참조가 자동으로 생성됩니다. 다음 예제에서는 ScriptManager 컨트롤이 포함된 페이지를 보여 줍니다.

<asp:ScriptManager  ID="scriptManager" />

다음 예제에서는 네임스페이스를 등록하고 클래스를 만든 다음 해당 클래스를 등록하는 방법을 보여 줍니다.

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
    this._firstName = firstName;
    this._lastName = lastName;
    this._emailAddress = emailAddress;
}

Demo.Person.prototype = {

    getFirstName: function() {
        return this._firstName;
    },

    getLastName: function() {
        return this._lastName;
    },

    getName: function() {
        return this._firstName + ' ' + this._lastName;
    },

    dispose: function() {
        alert('bye ' + this.getName());
    }
}
Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);

// Notify ScriptManager that this is the end of the script.
if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Namespace</title>
</head>

<body>
    <form id="Main" >
        <asp:ScriptManager  ID="scriptManager" />
    </form>

    <div>
        <p>This example creates an instance of the Person class 
            and puts it in the "Demo" namespace.</p>

        <input id="Button1" value="Create Demo.Person" 
            type="button" onclick="return OnButton1Click()" />

    </div>

    <script type="text/javascript" src="Namespace.js"></script>
    <script type="text/javascript" language="JavaScript">

    function OnButton1Click() 
    {
        var testPerson = new Demo.Person(  
            'John', 'Smith', 'john.smith@example.com');
        alert(testPerson.getFirstName() + " " +    
            testPerson.getLastName() );

        return false;
    }
    </script>
</body>
</html>

액세스 한정자

대부분의 개체 지향 프로그래밍 언어에는 액세스 한정자 개념이 포함되어 있습니다. 액세스 한정자를 사용하면 프로그램 외부, 동일한 네임스페이스 내의 내부 클래스 또는 특정 코드 블록 내에서만 등과 같이 클래스 또는 멤버를 사용할 수 있는 컨텍스트를 지정할 수 있습니다. JavaScript에는 액세스 한정자가 없지만 Microsoft AJAX 라이브러리에서는 이름이 밑줄 문자("_")로 시작하는 멤버는 전용 멤버로 간주하여 멤버가 속한 클래스 외부에서는 액세스할 수 없도록 하는 규칙을 따릅니다.

상속

상속은 한 클래스가 다른 클래스에서 파생시키는 기능입니다. 파생 클래스는 기본 클래스의 모든 필드, 속성, 메서드 및 이벤트를 자동으로 상속합니다. 또한 새 멤버를 추가하거나 기본 클래스의 기존 멤버를 재정의하여 해당 동작을 변경합니다.

다음 예제에서는 스크립트에 정의된 두 개의 클래스인 Person 및 Employee를 보여 줍니다. 여기서 Employee는 Person에서 파생됩니다. 두 클래스 모두 전용 필드의 사용을 보여 주며 공용 속성 및 메서드가 포함되어 있습니다. 또한 Employee는 Person 클래스의 toString 구현을 재정의하며 기본 클래스 기능을 사용합니다.

Type.registerNamespace("Demo");

Demo.Person = function(firstName, lastName, emailAddress) {
    this._firstName = firstName;
    this._lastName = lastName;
    this._emailAddress = emailAddress;
}

Demo.Person.prototype = {
    getFirstName: function() {
        return this._firstName;
    },

    getLastName: function() {
        return this._lastName;
    },

    getEmailAddress: function() {
        return this._emailAddress;
    },
    setEmailAddress: function(emailAddress) {
        this._emailAddress = emailAddress;
    },

    getName: function() {
        return this._firstName + ' ' + this._lastName;
    },

    dispose: function() {
        alert('bye ' + this.getName());
    },

    sendMail: function() {
        var emailAddress = this.getEmailAddress();

        if (emailAddress.indexOf('@') < 0) {
            emailAddress = emailAddress + '@example.com';
        }
        alert('Sending mail to ' + emailAddress + ' ...');
    },

    toString: function() {
        return this.getName() + ' (' + this.getEmailAddress() + ')';
    }
}

Demo.Person.registerClass('Demo.Person', null, Sys.IDisposable);
Demo.Employee = function(firstName, lastName, emailAddress, team, title) {
    Demo.Employee.initializeBase(this, [firstName, lastName, emailAddress]);

    this._team = team;
    this._title = title;
}

Demo.Employee.prototype = {

    getTeam: function() {
        return this._team;
    },
    setTeam: function(team) {
        this._team = team;
    },

    getTitle: function() {
        return this._title;
    },
    setTitle: function(title) {
        this._title = title;
    },
    toString: function() {
        return Demo.Employee.callBaseMethod(this, 'toString') + '\r\n' + this.getTitle() + '\r\n' + this.getTeam();
    }
}
Demo.Employee.registerClass('Demo.Employee', Demo.Person);
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Inheritance</title>
</head>

<body>
    <form id="Main" >
        <asp:ScriptManager  ID="scriptManager" />
    <script type="text/javascript" src="Inheritance.js"></script>
    </form>

    <h2>Inheritance</h2>
    <p />

    <div>
        This file contains two classes defined in script: Person and Employee, where
        Employee derives from Person.
        <p />

        Each class has private fields, and public properties and methods. In addition,
        Employee overrides the toString implementation, and in doing so, it uses the
        base class functionality.
        <p />

        This example puts the Person class in the "Demo" namespace.
        <p />
    </div>


    <div>
        <ul>
            <li><a href="#" onclick="return OnTestNewClick()">Object Creation</a></li>
            <li><a href="#" onclick="return OnTestDisposeClick()">Object Dispose</a></li>
            <li><a href="#" onclick="return OnTestPrivatePropertyClick()">Public vs. Private Properties</a></li>
            <li><a href="#" onclick="return OnTestInstanceMethodClick()">Instance Methods</a></li>
            <li><a href="#" onclick="return OnTestOverrideMethodClick()">Overriden Methods</a></li>
            <li><a href="#" onclick="return OnTestInstanceOfClick()">Instance Of Check</a></li>
        </ul>
    </div>

    <script type="text/javascript" language="JavaScript">

    function GetTestPerson() 
    {
        return new Demo.Person('Jane', 'Doe', 'jane.doe@example.com');
    }

    function GetTestEmployee() 
    {
        return new Demo.Employee('John', 'Doe', 'john.doe@example.com', 'Platform', 'Programmer');
    }

    function OnTestNewClick() {
        var aPerson = GetTestPerson();

        alert(aPerson.getFirstName());
        alert(aPerson);
        alert(Object.getType(aPerson).getName());

        var testPerson = GetTestPerson();
        alert(testPerson.getFirstName());
        alert(testPerson);

        return false;
    }

    function OnTestDisposeClick() {
        var aPerson = GetTestEmployee();
        alert(aPerson.getFirstName());
        aPerson.dispose();
    }

    function OnTestPrivatePropertyClick() {
        var aPerson = GetTestEmployee();
        alert('aPerson._firstName = ' + aPerson._firstName);
        alert('aPersona.getFirstName() = ' + aPerson.getFirstName());

        return false;
    }

    function OnTestInstanceMethodClick() {
        var aPerson = GetTestEmployee();
        aPerson.sendMail('Hello', 'This is a test mail.');

        return false;
    }

    function OnTestOverrideMethodClick() {
        var testPerson = GetTestEmployee();
        alert(testPerson);

        return false;
    }

    function OnTestInstanceOfClick() {
        var aPerson = GetTestEmployee();
        if (Demo.Employee.isInstanceOfType(aPerson)) {
            alert(aPerson.getName() + ' is an Employee instance.\r\nTitle property: ' + aPerson.getTitle());
        }

        return false;
    }

    </script>
</body>
</html>

인터페이스

인터페이스는 이를 구현하는 클래스의 입력 및 출력 요구 사항을 정의합니다. 이를 통해 클래스가 구현하는 다른 기능과 관계없이 동일한 인터페이스를 구현하는 클래스와 함수가 상호 작용할 수 있습니다.

다음 예제에서는 Tree 기본 클래스와 IFruitTree 인터페이스를 정의합니다. 두 파생 클래스인 Apple 및 Banana는 IFruitTree 인터페이스를 구현하지만 Pine 클래스는 그렇지 않습니다. IFruitTree 인터페이스를 구현하는 클래스는 bearFruit 멤버가 해당 클래스의 멤버인지 확인합니다.

Type.registerNamespace("Demo.Trees");

Demo.Trees.IFruitTree = function() {}
Demo.Trees.IFruitTree.Prototype = {
    bearFruit: function(){}
}
Demo.Trees.IFruitTree.registerInterface('Demo.Trees.IFruitTree');


Demo.Trees.Tree = function(name) {
    this._name = name;
}
Demo.Trees.Tree.prototype = {
    returnName: function() {
        return this._name;
    },

    toStringCustom: function() {
        return this.returnName();
    },

    makeLeaves: function() {}
}
Demo.Trees.Tree.registerClass('Demo.Trees.Tree');


Demo.Trees.FruitTree = function(name, description) {
    Demo.Trees.FruitTree.initializeBase(this, [name]);
    this._description = description;
}
Demo.Trees.FruitTree.prototype.bearFruit = function() {
        return this._description;
}
Demo.Trees.FruitTree.registerClass('Demo.Trees.FruitTree', Demo.Trees.Tree, Demo.Trees.IFruitTree);

Demo.Trees.Apple = function() {
    Demo.Trees.Apple.initializeBase(this, ['Apple', 'red and crunchy']);
}
Demo.Trees.Apple.prototype = {
    makeLeaves: function() {
        alert('Medium-sized and desiduous');
    },
    toStringCustom: function() {
        return 'FruitTree ' + Demo.Trees.Apple.callBaseMethod(this, 'toStringCustom');
    }
}
Demo.Trees.Apple.registerClass('Demo.Trees.Apple', Demo.Trees.FruitTree);

Demo.Trees.GreenApple = function() {
    Demo.Trees.GreenApple.initializeBase(this);
    // You must set the _description feild after initializeBase
    // or you will get the base value.
    this._description = 'green and sour';
}
Demo.Trees.GreenApple.prototype.toStringCustom = function() {
    return Demo.Trees.GreenApple.callBaseMethod(this, 'toStringCustom') + ' ... its GreenApple!';
}
Demo.Trees.GreenApple.registerClass('Demo.Trees.GreenApple', Demo.Trees.Apple);


Demo.Trees.Banana = function(description) {
    Demo.Trees.Banana.initializeBase(this, ['Banana', 'yellow and squishy']);
}
Demo.Trees.Banana.prototype.makeLeaves = function() {
    alert('Big and green');
}
Demo.Trees.Banana.registerClass('Demo.Trees.Banana', Demo.Trees.FruitTree);



Demo.Trees.Pine = function() {
    Demo.Trees.Pine.initializeBase(this, ['Pine']);
}
Demo.Trees.Pine.prototype.makeLeaves = function() {
    alert('Needles in clusters');
}
Demo.Trees.Pine.registerClass('Demo.Trees.Pine', Demo.Trees.Tree);

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Interface</title>
</head>

<body>
    <form id="Main" >
        <asp:ScriptManager  ID="scriptManager" />
    </form>

    <h2>Interface</h2>
    <p />

    <div>
        This file contains a Tree base class, and an IFruitTree interface.
        Apple and Banana, two derived classes implement that interface, whereas,
        Pine does not implement that interface.
        <p />
    </div>

    <script type="text/javascript" src="Interface.js"></script>

    <div>
        <ul>
                <li><a href="#" onclick="return OnTestNewClick()">Object Creation</a></li>
                <li><a href="#" onclick="return OnTestImplementsClick()">Implements Check</a></li>
                <li><a href="#" onclick="return OnTestInterfaceMethodClick()">Call interface method</a></li>
        </ul>
    </div>

    <script type="text/javascript" language="JavaScript">

    function OnTestNewClick() {
        var apple = new Demo.Trees.Apple('Apple');
        alert(apple.returnName());
        apple.makeLeaves();

        return false;
    }

    function OnTestImplementsClick() {
        var apple = new Demo.Trees.Apple();
        if (Demo.Trees.IFruitTree.isImplementedBy(apple)) {
            alert('Apple implements IFruitTree');
        }
        else {
            alert('Apple does not implement IFruitTree');
        }

        var pine = new Demo.Trees.Pine();
        if (Demo.Trees.IFruitTree.isImplementedBy(pine)) {
            alert('Pine implements IFruitTree');
        }
        else {
            alert('Pine does not implement IFruitTree');
        }

        return false;
    }

    function OnTestInterfaceMethodClick() {
        var apple = new Demo.Trees.Apple();
        ProcessTree(apple);

        var pine = new Demo.Trees.Pine();
        ProcessTree(pine);

        var banana = new Demo.Trees.Banana();
        ProcessTree(banana);

        var g = new Demo.Trees.GreenApple();
        ProcessTree(g);

        return false;
    }

    function ProcessTree(tree) {
        alert('Current Tree ' + tree.returnName());
        alert(tree.toStringCustom());
        if (Demo.Trees.IFruitTree.isImplementedBy(tree)) {
            alert(tree.returnName() + ' implements IFruitTree; Fruit is ' + tree.bearFruit());
        }
    }
    </script>
</body>
</html>

열거형

열거형은 명명된 정수 상수 집합이 들어 있는 클래스입니다. 다음 예제에서처럼 속성 등의 값에 액세스합니다.

myObject.color = myColorEnum.red

열거형은 정수 표현에 대해 쉽게 읽을 수 있는 대안을 제공합니다. Microsoft AJAX 라이브러리의 열거형에 대한 자세한 내용은 Type.registerEnum 메서드(ASP.NET AJAX)를 참조하십시오.

다음 예제에서는 16진수 값을 나타내는 명명된 색의 열거형을 정의합니다.

Type.registerNamespace("Demo");

// Define an enumeration type and register it.
Demo.Color = function(){};
Demo.Color.prototype = 
{
    Red:    0xFF0000,
    Blue:   0x0000FF,
    Green:  0x00FF00,
    White:  0xFFFFFF 
}
Demo.Color.registerEnum("Demo.Color");
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Enumeration</title>
</head>

<body>
    <form id="Main" >
        <asp:ScriptManager  ID="scriptManager" />
    </form>

    <div>
        <p>This example creates an Enumeration of colors
            and applies them to page background.</p>

        <select id="ColorPicker" 
            onchange="ChangeColor(options[selectedIndex].value)">
            <option value="Red" label="Red" />
            <option value="Blue" label="Blue" />
            <option value="Green" label="Green" />
            <option value="White" label="White" />
        </select>

    </div>

    <script type="text/javascript" src="Enumeration.js"></script>
    <script type="text/javascript" language="JavaScript">

    function ChangeColor(value) 
    {
         document.body.bgColor = eval("Demo.Color." + value + ";");
    }

    </script>

</body>
</html>

리플렉션

리플렉션은 런타임에 프로그램의 구조와 구성 요소를 검사하는 기능입니다. 리플렉션을 구현하는 API는 Type 클래스의 확장입니다. 이러한 메서드를 사용하면 개체의 상속 대상, 개체가 특정 인터페이스를 구현하는지 여부, 개체가 특정 클래스의 인스턴스인지 여부 등과 같은 개체 관련 정보를 수집할 수 있습니다.

다음 예제에서는 리플렉션 API를 사용하여 이전 인터페이스 예제의 GreenApple 클래스를 테스트합니다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Reflection</title>
</head>

<body>
    <form id="Main" >
        <asp:ScriptManager  ID="scriptManager" />
    </form>

    <div>
        <p>This example tests the Demo.Trees.GreenApple class 
            against various reflection APIs.</p>

        <input id="Button1" value="Check Type" 
            type="button" onclick="return OnButton1Click()" />
        <input id="Button2" value="Check Inheritance" 
            type="button" onclick="return OnButton2Click()" />
        <input id="Button3" value="Check Interface" 
            type="button" onclick="return OnButton3Click()" />

    </div>

    <script type="text/javascript" src="Interface.js"></script>
    <script type="text/javascript" language="JavaScript">

    var g = new Demo.Trees.GreenApple();
    var gt = Demo.Trees.GreenApple;
    var a = new Array(
        Demo.Trees.Apple, 
        Demo.Trees.Tree, 
        Demo.Trees.Pine,
        Demo.Trees.IFruitTree,
        Sys.IContainer);

    function OnButton1Click() 
    {
        for (var i = 0; i < a.length; i ++)
        {
            if (a[i].isInstanceOfType(g))
            {
                alert(gt.getName() + " is a " + a[i].getName() + ".");
            }
            else alert(gt.getName() + " is not a " + a[i].getName() + ".");
        }
    }

    function OnButton2Click() 
    {
        for (var i = 0; i < a.length; i ++)
        {
            if (gt.inheritsFrom(a[i]))
            {
                alert(gt.getName() + " inherits from " + a[i].getName() + ".");
            }
            else alert(gt.getName() + " does not inherit from " + a[i].getName() + ".");
        }
    }

    function OnButton3Click() 
    {
        for (var i = 0; i < a.length; i ++)
        {
            if (Type.isInterface(a[i]))
            {
                if (gt.implementsInterface(a[i]))
                {
                    alert(gt.getName() + " implements the " + a[i].getName() + " interface.");
                }
                else alert(gt.getName() + " does not implement the " + a[i].getName() + " interface.");
            }
            else alert(a[i].getName() + " is not an interface.");
        }
    }
    </script>
</body>
</html>

JavaScript 기본 형식에 대한 확장 사용

JavaScript 기본 형식에 대한 확장에서는 이러한 형식에 대한 추가 기능을 제공합니다. 이러한 확장에 대한 자세한 내용은 다음 항목을 참조하십시오.

Sys.Debug 클래스에서는 포괄적인 디버깅 기능을 제공합니다. 자세한 내용은 AJAX 응용 프로그램 디버깅 및 추적 개요Sys.Debug 클래스 개요를 참조하십시오.

Microsoft AJAX 라이브러리를 기반으로 하는 구성 요소를 만드는 경우 ScriptManager 컨트롤을 통해 자동으로 관리되는 디버그 및 릴리스 버전의 스크립트 파일을 만들 수 있습니다. 디버그 버전의 스크립트 파일은 스크립트 파일 이름에 ".debug"를 포함하여 식별할 수 있습니다. 예를 들어 다음 스크립트 파일 이름은 일반 정품 버전의 파일과 디버그 버전의 파일을 식별합니다.

  • MyScript.js(일반 정품)

  • MyScript.debug.js(디버그)

클라이언트 스크립트를 ASP.NET 웹 응용 프로그램에 통합

ASP.NET 웹 페이지는 다음 예제에서처럼 스크립트 파일을 <script> 블록에서 참조하는 방식으로 해당 스크립트 파일에 액세스할 수 있습니다.

<script type="text/javascript" src="MyScript.js"></script>

그러나 이러한 방법으로 호출한 스크립트는 부분 페이지 렌더링에 관여하거나 Microsoft AJAX 라이브러리의 특정 구성 요소에 액세스할 수 없습니다. AJAX 사용 ASP.NET 웹 응용 프로그램에서 스크립트 파일을 부분 페이지 렌더링에 사용할 수 있도록 하려면 스크립트를 페이지의 ScriptManager 컨트롤에 등록해야 합니다. 스크립트 파일을 등록하려면 파일 질문을 가리키고 이를 Scripts 컬렉션에 추가하는 ScriptReference 개체를 만듭니다. 다음 예제에서는 이 작업을 태그에서 수행하는 방법을 보여 줍니다.

<asp:ScriptManager ID="SMgr" >
  <Scripts>
    <asp:ScriptReference path="MyScript.js" />
  </Scripts>
</asp:ScriptManager> 

ScriptManager 컨트롤에서 스크립트를 올바르게 처리하도록 하려면 각 파일의 끝에 Sys.Application.notifyScriptLoaded 메서드에 대한 호출이 포함되어 있어야 합니다. 이 호출은 파일이 로드되었음을 응용 프로그램에 알립니다. 다음 예제에서는 이를 위해 사용하는 코드를 보여 줍니다.

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

또한 .js 파일을 관리 코드 어셈블리에 리소스로 포함할 수도 있습니다. 이 작업은 ASP.NET 서버 컨트롤을 클라이언트 스크립트에 구현된 AJAX 기능을 사용하여 만드는 경우에 수행할 수 있습니다. 스크립트가 어셈블리에 포함되어 있으면 해당 스크립트에 알림 문을 포함할 필요가 없습니다. 또한 스크립트 참조에 path 특성을 지정할 필요가 없습니다. 하지만 다음 예제에서처럼 어셈블리의 이름을 파일 이름 확장명 없이 지정해야 합니다.

<asp:ScriptManager ID="SMgr" >
  <Scripts>
    <asp:ScriptReference 
        Name="MyScript.js" Assembly="MyScriptAssembly"/>
  </Scripts>
</asp:ScriptManager> 
참고:

스크립트 라이브러리가 포함된 대부분의 컨트롤은 해당 스크립트를 내부적으로 참조하므로 이 시나리오는 페이지 개발자에게는 일반적이지 않습니다. 자세한 내용은 연습: 어셈블리에 JavaScript 파일을 리소스로 포함을 참조하십시오.

코드에서 스크립트 참조를 만들어 Scripts 컬렉션에 추가함으로써 스크립트를 프로그래밍 방식으로 등록할 수도 있습니다. 자세한 내용은 동적으로 스크립트 참조 할당을 참조하십시오.

부분 페이지 업데이트에 필요한 스크립트는 ScriptManager 컨트롤의 등록 메서드를 사용하여 등록할 수 있습니다. 이 메서드는 다음과 같이 사용할 수 있습니다.

  • 코드에서 클라이언트 스크립트를 생성하려면 스크립트의 블록을 문자열로 빌드하여 RegisterClientScriptBlock 메서드로 전달합니다.

  • Microsoft AJAX 라이브러리 종속성이 없는 독립 실행형 스크립트 파일을 추가하려면 RegisterClientScriptInclude 메서드를 사용합니다.

  • 어셈블리에 포함된 스크립트 파일을 추가하려면 RegisterClientScriptInclude 메서드를 사용합니다.

    참고:

    이러한 메서드를 사용하여 등록한 스크립트는 지역화가 지원되지 않습니다.

스크립트 등록 메서드 및 해당 사용 방법에 대한 전체 목록을 보려면 ScriptManager 컨트롤 개요를 참조하십시오.

등록하는 스크립트 블록 또는 인라인 스크립트는 페이지의 <form> 요소 내에 있어야 합니다. 그렇지 않으면 스크립트가 ScriptManager 컨트롤에 등록되지 않고 ASP.NET AJAX 기능에도 액세스할 수 없습니다. 자세한 내용은 Sys.Application.initialize 메서드를 참조하십시오.

참고 항목

작업

샘플 AJAX 응용 프로그램

개념

부분 페이지 렌더링 개요

ASP.NET AJAX 개요

ASP.NET 웹 페이지의 클라이언트 스크립트

클라이언트 구성 요소 및 컨트롤 만들기

참조

Type 클래스