'Language'에 해당되는 글 463건

  1. 2013.07.03 XML 스키마
  2. 2013.05.22 마우스 커서 포지션 이동
  3. 2013.04.29 XMLHttpRequest 고급 기능 1
  4. 2013.04.29 XMLHttpRequest Level 2
  5. 2013.04.29 XMLHttpRequest
  6. 2013.04.23 인코딩 - 8859_1의 비밀(?)
  7. 2013.04.23 Tomcat과 한글 인코딩
  8. 2013.02.22 자바스크립트
  9. 2013.02.21 html5 태그 지원 테스트
  10. 2013.02.19 find, filter, children

XML 스키마

Language/XML 2013. 7. 3. 11:18

4장 XML 스키마(Schema)

요점 및 보강 자료

1. 스키마란

  • XML 문서의 구조와 엘리먼트, 속성들의 관계를 정의하여 다양한 자료형을 사용할 수 있도록 정의된 문서 구조

2. 스키마 구조의 장점

  • xml 문법을 따른다.
  • 풍부한 데이터형을 제공한다.
  • 데이터의 제약 조건을 세밀하게 정의한다.

3. DTD 구조와 스키마 구조의 간단한 차이점

    DTD

    스키마

    XML 1.0에서 제정

    XML 2.0에서 제정

    익스플로러 4.0부터 도입

    익스플로러 5.0부터 도입

    확장자 DTD

    확장자 XSD

    데이터타입을 지원하는 기능이 부족

    풍부한 데이터 타입을 지원

    엘리먼트속성 등의 지원 기능이 미흡

    엘리먼트속성 등의 지원 기능이 가능

    데이터의 정렬이 어려움

    데이터의 정렬이 가능

4. XSD 문서의 기본 형식

  • 첫줄에 XML 문서와 같이 선언문부터 정의
  • <?xml version="1.0" encoding="EUC-KR"?>

  • 두 번째줄에 <schema> 태그를 정의 : XML 스키마를 정의하는 문서임을 표시
  • <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

           ... XSD 정의 문장

    </xsd:schema>

5. 이름 공간(namespace)

  • 이름공간이란?
    • 서로 다르게 작성한 XML 문서에도 공통적인 엘리먼트가 있을 수 있다. 이 엘리먼트는 이름은 같지만, 내용은 전혀 다르다. 이 엘리먼트를 구별하기 위해 이름 공간을 사용한다.
      • 어떤 이름이 통용되는 범위
    • 접두사와 엘리먼트는 콜론(:)으로 구분
  • 이름공간 정의
  • <접두사:태그명  xmlnx:접두사="홈페이지주소" />

6. XSD와 XML 문서 연결하기

7. 엘리먼트 정의

  • <element>태그
    • <xsd:element name="엘리먼트이름" type="xsd:데이터형">

  • 데이터형
    • number : 임의의 수를 처리하는 데이터 타입

      int : 정수형을 처리

      float : 실수형을 처리

      date : 날짜를 처리

      dateTime : 날짜와 시간을 처리

      boolean : 논리값을 처리

      char : 문자를 처리

      string : 문자열을 처리

     

      <?xml version="1.0" encoding="EUC-KR"?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

              <xsd:element name="도서목록" type="xsd:string">

              </xsd:element>

      </xsd:schema>

    • 도서목록02.xml

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록01.xsd">

              도서목록 관리 -  일반 문자열을 나열

      </도서목록>

  • <complexType> 태그
    • 하위 엘리먼트를 포함하거나 속성이 있는 엘리먼트를 선언 (복잡한 구조)

     

  • <simpleType>태그
    • 속성이나 하위 엘리먼트를 포함하지 않는 엘리먼트 (간단한 구조)

     

  • <sequence> 태그
    • 자식 엘리먼트가 순서대로 와야 할 때 사용

      <도서목록>

           <도서>

               <분류>컴퓨터</분류>

                <제목>XML</제목>

               <출판사>정보</출판사>

               <저자>박준서, 최배근</저자>

           </도서>

      </도서목록>

      <?xml version="1.0" encoding="EUC-KR"?>

      <!DOCTYPE 도서목록[

      <!ELEMENT 도서목록 (도서) >

      <!ELEMENT 도서 (분류,제목,출판사,저자) >

      <!ELEMENT 분류 (#PCDATA) >

      <!ELEMENT 제목 (#PCDATA) >

      <!ELEMENT 출판사 (#PCDATA)

      <!ELEMENT 저자 (#PCDATA) >

      ]>

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록04.xsd">

        ☞ 도서목록05.xml 파일에서 도서목록루트엘리먼트 안에  

                도서목록04.xsd 문서를 참조하라고 정의

              <도서>

                      <분류>컴퓨터</분류>

                      <제목>XML</제목>

                      <출판사>정보</출판사>

                      <저자>박준서, 최배근</저자>

              </도서>

      </도서목록>

      <?xml version="1.0" encoding="EUC-KR"?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

        <xsd:element name="도서목록">

          <xsd:complexType>    ☞ 도서목록 엘리먼트는 하위 엘리먼트를 포함

            <xsd:sequence>     ☞ 자식 엘리먼트들이 정의한 순서대로 반드시 정의

                                도서엘리먼트와 하위 엘리먼트는 생략 불가능

              <xsd:element name="도서">

                <xsd:complexType>

                  <xsd:sequence>

       

                    <xsd:element name="분류" type="xsd:string" />

                    <xsd:element name="제목" type="xsd:string" />

                    <xsd:element name="출판사" type="xsd:string" />

                    <xsd:element name="저자" type="xsd:string" />

        ☞ 분류,제목,출판사,저자태그는 문자형 생략 불가능

                  </xsd:sequence>

                </xsd:complexType>

              </xsd:element>

            </xsd:sequence>

          </xsd:complexType>

        </xsd:element>

      </xsd:schema>

      <?xml version="1.0" encoding="euc-kr" ?>

      <members>

              <member>

                      <name>홍길동</name>

                      <phone_no>031-111-2323</phone_no>

              </member>

              <member>

                      <name>김유신</name>

                      <phone_no>02-111-1234</phone_no>

              </member>

      </members>

      <?xml version="1.0" encoding="euc-kr" ?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

      <xsd:element name="members">

       <xsd:complexType>

        <xsd:sequence>

          <xsd:element name="member" minOccurs="1" maxOccurs="unbounded">

           <xsd:complexType>

             <xsd:sequence>

              <xsd:element name="name" type="xsd:string" />

              <xsd:element name="phone_no" type="xsd:string"

                                                              minOccurs="1" maxOccurs="2"/>

             </xsd:sequence>

           </xsd:complexType>

          </xsd:element>

        </xsd:sequence>

       </xsd:complexType>

      </xsd:element>

      </xsd:schema>

      <?xml version="1.0" encoding="euc-kr" ?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

       

         <!-- 루트요소 선언 -->

         <xsd:element name="members">

              <xsd:complexType>

                    <xsd:sequence>

                          <xsd:element name="member"   type="memberType"  

                                                          minOccurs="1" maxOccurs="unbounded" />

                    </xsd:sequence>

              </xsd:complexType>

         </xsd:element>

       

         <!-- memberType 선언 -->

         <xsd:complexType name="memberType">

              <xsd:sequence>

                    <xsd:element name="name" type="xsd:string" />

                    <xsd:element name="phone_no" type="xsd:string" />

              </xsd:sequence>

         </xsd:complexType>

       

      </xsd:schema>

  • <minOccurs> 태그
    • 엘리먼트의 최소 반복 횟수를 정의
    • 생략시 기본값 = 1
    • 0으로 정의시 : 엘리먼트는 생략
    • 1로 정의시 : 반드시 엘리먼트 1번 정의

     

  • <maxOccurs> 태그
    • 엘리먼트의 최대 반복 횟수를 정의
    • 생략시 기본값 = 1
    • 1로 정의시 : 무조건 한번만 정의
    • unbound로 정의시 반복 횟수에 제한 받지 않고 사용
    • 도서목록14.xml

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록13.xsd">

              <도서>

                      <분류>컴퓨터</분류>

                      <제목>XML</제목>

                      <출판사>정보</출판사>

                      <저자>박준서</저자>

                      <저자>최배근</저자>

              </도서>        

              <도서>

                      <분류>컴퓨터</분류>

                      <저자>박준서</저자>             

              </도서>

      </도서목록>

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" minOccurs="1" maxOccurs="unbounded">

        ☞ 도서엘리먼트를 한번 이상 정의 (+)

                <complexType>

                  <sequence>

                    <element name="분류" type="string" minOccurs="1" maxOccurs="1" />

                ☞ 분류엘리먼트를 한번은 꼭 정의 (  )

                    <element name="제목" type="string" minOccurs="0" maxOccurs="1" />

                       ☞ 제목 엘리먼트를 정의하지 않거나 한번 정의 (?)

                    <element name="출판사" type="string" minOccurs="0" maxOccurs="unbounded" />

                       ☞ 출판사 엘리먼트를 정의하지 않거나 여러번 정의 (*)

                    <element name="저자" type="string" minOccurs="1" maxOccurs="2" />

                ☞ 저자 엘리먼트를 한번 정의 또는 2번까지 정의

                  </sequence>

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • <choice> 태그
    • dtd에서의 |기호와 같은 역할
    • 여러 가지 엘리먼트 중에서 한 개만을 정의

      <?xml version="1.0" encoding="EUC-KR"?>

      <!DOCTYPE 도서목록[

        <!ELEMENT 도서목록 (도서) >

        <!ELEMENT 도서 (분류|제목|출판사|저자) >

        <!ELEMENT 분류 (#PCDATA) >

        <!ELEMENT 제목 (#PCDATA) >

        <!ELEMENT 출판사 (#PCDATA)

        <!ELEMENT 저자 (#PCDATA) >

      ]>

    • 도서목록10.xml
    • <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록09.xsd">

              <도서>

                      <제목>XML</제목>

              </도서>

      </도서목록>

    • 도서목록09.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

       

              <element name="도서">

                <complexType>

                  <choice>    

        ☞ 분류,제목,출판사,저자 엘리먼트 중에서 한 개를 선택해서 정의

                    <element name="분류" type="string" />

                    <element name="제목" type="string" />

                    <element name="출판사" type="string" />

                    <element name="저자" type="string" />

       

                  </choice>

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

    • member2.xml : <member>의 자식 요소로 <name>과 <phone_no> 두 개의 요소를 가지거나

                                           <lname>, <fname>, <phone_no> 세 개의 요소를 가질 수 있는 예

      <?xml version="1.0" encoding="EUC-KR"?>

      <members>

              <member>

                      <name>홍길동</name>

                      <phone_no>031-111-2323</phone_no>

              </member>

              <member>

                      <lname>김</lname>

                      <fname>유신</fname>

                      <phone_no>031-111-2323</phone_no>

              </member>

      </members>

    • member2.xsd

      <?xml version="1.0" encoding="euc-kr" ?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

       

         <!-- 루트요소 선언 -->

         <xsd:element name="members">

              <xsd:complexType>

                    <xsd:sequence>

                          <xsd:element name="member" type="memberType"  

                                                       minOccurs="1" maxOccurs="unbounded" />

                    </xsd:sequence>

              </xsd:complexType>

         </xsd:element>

       

         <!-- memberType 선언 -->

         <xsd:complexType name="memberType">

               <xsd:choice>

                    <xsd:sequence>

                          <xsd:element name="name" type="xsd:string" />

                          <xsd:element name="phone_no" type="xsd:string" />

                    </xsd:sequence>

                    <xsd:sequence>

                          <xsd:element name="lname" type="xsd:string" />

                          <xsd:element name="fname" type="xsd:string" />

                          <xsd:element name="phone_no" type="xsd:string" />

                    </xsd:sequence>

               </xsd:choice>

         </xsd:complexType>

      </xsd:schema>

  • <all> 태그
    • 엘리먼트의 순서를 생각하지 않을 때 사용
    • all 태그를 사용할 경우 복잡성을 줄이기 위한 제약사항
      • 내부의 요소들은 반복이 1회까지로 제한
      • choice 태그 안에서 사용할 수 없는 등 다른 복합자와 함께 사용될 때 제약이 존재
    • 도서목록12.xml
    • <?xml version="1.0" encoding="EUC-KR"?>

       

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록11.xsd">

              <도서>

                      <제목>XML</제목>

                      <분류>컴퓨터</분류>             

                      <저자>박준서</저자>

                      <출판사>정보</출판사>           

              </도서>

      </도서목록>

    • 도서목록11.xsd
    • <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서">

                <complexType>

                  <all>

        ☞ 분류,제목,출판사,저자 엘리먼트는 순서를 생각하지 않는다.

                    <element name="분류" type="string" />

                    <element name="제목" type="string" />

                    <element name="출판사" type="string" />

                    <element name="저자" type="string" />

                  </all>

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

    • member2-1.xml : <member>의 자식 요소로 <name>과 <phone_no> 요소가 순서가 없을때

      <?xml version="1.0" encoding="EUC-KR"?>

      <members>

              <member>

                      <name>홍길동</name>

                      <phone_no>031-111-2323</phone_no>

              </member>

      </members>

    • member2-1.xsd

      <?xml version="1.0" encoding="euc-kr" ?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

       

         <!-- 루트요소 선언 -->

         <xsd:element name="members">

              <xsd:complexType>

                    <xsd:sequence>

                          <xsd:element name="member" type="memberType"  

                                                       minOccurs="1" maxOccurs="unbounded" />

                    </xsd:sequence>

              </xsd:complexType>

         </xsd:element>

       

         <!-- memberType 선언 -->

         <xsd:complexType name="memberType">

               <xsd:all>

                          <xsd:element name="name" type="xsd:string" />

                          <xsd:element name="phone_no" type="xsd:string" />

               </xsd:all>

         </xsd:complexType>

      </xsd:schema>

       

  • <default> 태그
    • 엘리먼트의 값이 정의되지 않으면 default로 정의된 값을 할당

     

  • <fixed> 태그
    • 엘리먼트에 정의되는 값이 생략 또는
    • fixed로 정의된 값이 엘리먼트의 값으로 정의

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록15.xsd">

              <도서>

                      <분류></분류>

                      <제목>XML</제목>

              </도서>

      </도서목록>

    • 도서목록15.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" minOccurs="1" maxOccurs="unbounded">

                <complexType>

                  <sequence>

                    <element name="분류" type="string" default="컴퓨터" />

          ☞ 분류 엘리먼트의 값을 정의하지 않으면 "컴퓨터" 값으로 정의됨

          ☞ 분류 엘리먼트의 값을 정의하면 정의한 값이 사용

                    <element name="제목" type="string" fixed="XML" />

          ☞ 제목 엘리먼트의 값을 생략시 "XML"값으로 정의됨

          ☞ 제목 엘리먼트의 값을 "XML"이 아닌 다른 값으로 정의하면  오류

                  </sequence>

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • <group> 태그
    • 엘리먼트의 반복을 쉽게 정의
    • 반복되는 엘리먼트의 그룹을 <group>태그로 묶은 후 XSD에서 필요할 때 가져와서 사용

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록17.xsd">

              <도서>

                      <분류>컴퓨터</분류>

                      <제목>XML</제목>

                      <출판사>정보</출판사>

                      <저자>박준서</저자>

              </도서>

      </도서목록>

    • 도서목록17.xsd

      <?xml version="1.0" encoding="EUC-KR" ?>

      <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

       

          <xsd:group name="myItem">

            <xsd:sequence>

              <xsd:element name="분류" type="xsd:string" />

              <xsd:element name="제목" type="xsd:string" />

              <xsd:element name="출판사" type="xsd:string" />

              <xsd:element name="저자" type="xsd:string" />

            </xsd:sequence>

          </xsd:group>

        

          <xsd:element name="도서목록">

            <xsd:complexType>

              <xsd:sequence>

                <xsd:element name="도서">

                  <xsd:complexType>

                    <xsd:sequence>

                      <xsd:group ref="myItem" />

                    </xsd:sequence>

                  </xsd:complexType>

                </xsd:element>

              </xsd:sequence>

            </xsd:complexType>

          </xsd:element>

       

      </xsd:schema>

         

8. 어트리뷰트 정의

  • <attribute> 태그
    • <attribute  name="속성이름"     

                                    type="string"               => 데이터형

                                    default="값"                => 기본값 정의

                                    fixed="값"                   => 고정값 정의

                                    ref="속성명                 => 미리 정의된 속성이름

                                    use="값"                     => 구속조건

                                    id="값"                        => 고유한 값

                                    form="값>                  => 한정된 이름인지의 여부

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록19.xsd">

              <도서 분류="컴퓨터" 제목="XML" />

              <도서 분류="컴퓨터" />

      </도서목록>

    • 도서목록19.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                    <attribute name="분류" type="string" />

                  <attribute name="제목" type="string" />

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • 어트리뷰트에 고유한 값 정의하기
    • type 속성에 ID 유형을 정의

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록21.xsd">

              <도서 분류="컴퓨터1" 제목="XML" />

              <도서 분류="컴퓨터2" />

      </도서목록>

    • 도서목록21.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                  <attribute name="분류" type="ID" />

                  <attribute name="제목" type="string" />

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • use 속성
    • use 속성이 가지는 값
      • optional : 속성을 정의하지 않아도 됨
      • required : 꼭 속성을 정의해야 함
      • prohibited : 속성이 전혀 없다.

                                                   정의하지 않아도 되는 제목 속성을 정의

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록23.xsd">

              <도서 분류="컴퓨터" 제목="XML" />

              <도서 분류="컴퓨터" />

      </도서목록>

    • 도서목록23.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                    <attribute name="분류" type="string" use="required" />

                  <attribute name="제목" type="string" use="optional" />

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • default와 fixed 속성
    • default 속성 : 속성을 정의하지 않은 경우에 기본값으로 사용
    • fixed 속성 : 무조건 이 값만을 가지는 속성 정의시 사용
    • 도서목록26.xml : 도서 태그안에 "컴퓨터"라는 기본값을 가지는 분류 속성과

                                  "xml무작정따라하기"라는 고정값을 가지는 제목 속성을 정의

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록25.xsd">

              <도서 분류="컴퓨터" 제목="XML" />

              <도서 />

      </도서목록>

    • 도서목록25.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                  <attribute name="분류" type="string" default="컴퓨터" />

                  <attribute name="제목" type="string" fixed="XML 무작정 따라하기" />

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

  • <simpleType>태그
    • <enumeration>태그
      • 여러 개의 정의된 값 중에서 하나의 속성만을 선택
    • <length>태그
      • 어트리뷰트 데이터에 있는 문자의 개수를 정의
    • <minLength>태그
      • 어트리뷰트 데이터에 있는 문자의 최소 개수를 정의
    • <maxLength>태그
      • 어트리뷰터 데이터에 있는 문자의 최대 개수를 정의
    • <minInclusive>태그
      • 어트리뷰트 데이터의 최소 범위를 지정
    • <maxInclusive>태그
      • 어트리뷰트 데이터의 최대 범위를 지정

     

                          분류 속성은 "컴퓨터","소설","만화"라는 값중에 하나의 값만 가짐

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록27.xsd">

              <도서 분류="컴퓨터" 제목="XML" />

              <도서 분류="소설" 제목="비와그리움" />

      </도서목록>

    • 도서목록27.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                  <attribute name="분류">

                    <simpleType>

                      <restriction base="string">

                        <enumeration value="컴퓨터" />

                        <enumeration value="소설" />

                        <enumeration value="만화" />

                      </restriction>

                    </simpleType>

                  </attribute>

                  <attribute name="제목" type="string" />

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

       

                                                  분류 속성 값의 길이는 3개, 제목 속성 값의 길이는 최소 1개 최대 6개이다.

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록29.xsd">

              <도서 분류="컴퓨터" 제목="XML" />

              <도서 분류="소설1" 제목="비와그리움" />

      </도서목록>

    • 도서목록29.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

       

                  <attribute name="분류">

                    <simpleType>

                      <restriction base="string">

                        <length value="3" />

                      </restriction>

                    </simpleType>

                  </attribute>

                  

                  <attribute name="제목">

                    <simpleType>

                      <restriction base="string">

                        <minLength value="1" />

                        <maxLength value="6" />

                      </restriction>

                    </simpleType>

                  </attribute>

                  

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

    • 도서목록32.xml :  도서태그의 수량 속성은 0에서 10사이의 값을 가진다.

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록31.xsd">

              <도서 수량="10" />

      </도서목록>

    • 도서목록31.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                

                  <attribute name="수량">

                    <simpleType>

                      <restriction base="integer">

                        <minInclusive value="0" />

                        <maxInclusive value="10" />

                      </restriction>

                    </simpleType>

                  </attribute>

                  

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>

    • 도서목록34.xml : 도서의 자식태그인 분류 태그는 컴퓨터, 소설, 만화라는 값중에 하나의 값만 가진다.

      <?xml version="1.0" encoding="EUC-KR"?>

      <도서목록 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

               xsi:noNamespaceSchemaLocation="도서목록33.xsd">

              <도서>

                      <분류>컴퓨터</분류>

              </도서>

              <도서>

                      <분류>소설</분류>

              </도서>

      </도서목록>

    • 도서목록33.xsd

      <?xml version="1.0" encoding="EUC-KR"?>

      <schema xmlns="http://www.w3.org/2001/XMLSchema">

        <element name="도서목록">

          <complexType>

            <sequence>

              <element name="도서" maxOccurs="unbounded">

                <complexType>

                  <sequence>

                    <element name="분류">

                      <simpleType>

                        <restriction base="string">

                          <enumeration value="컴퓨터" />

                          <enumeration value="소설" />

                          <enumeration value="만화" />

                        </restriction>

                      </simpleType>

                    </element>

                  </sequence>

                </complexType>

              </element>

            </sequence>

          </complexType>

        </element>

      </schema>


출처 - http://linuxism.tistory.com/911

'Language > XML' 카테고리의 다른 글

참조, 예제 사이트  (0) 2016.12.13
WSDL(Web Services Description Language)  (0) 2016.12.12
XML, SOAP, WSDL, UDDI  (0) 2016.12.07
:

마우스 커서 포지션 이동

Language/JAVASCRIPT 2013. 5. 22. 13:19

function setCaretPosition(ctrl, pos)
{
    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange)
    {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

'Language > JAVASCRIPT' 카테고리의 다른 글

구글맵(차트)  (0) 2014.12.12
prototypejs  (0) 2013.11.13
XMLHttpRequest 고급 기능  (1) 2013.04.29
XMLHttpRequest Level 2  (0) 2013.04.29
XMLHttpRequest  (0) 2013.04.29
:

XMLHttpRequest 고급 기능

Language/JAVASCRIPT 2013. 4. 29. 19:40
http://msdn.microsoft.com/ko-kr/library/ie/hh673569%28v=vs.85%29.aspx#Enhanced_Event_Support

.NET Framework 3.0

Internet Explorer 10 및 JavaScript를 사용하는 Windows 스토어 앱은 새로운 표준에 대한 지원을 확장하고 일반적인 개발자 시나리오를 손쉽게 지원할 수 있도록 XMLHttpRequest 개체의 몇 가지 고급 기능을 제공합니다. 여기에는 다음과 같은 기능이 포함됩니다.

  • 플러그 인을 사용하지 않고 이미지, 동영상 및 오디오와 같은 이진 파일을 다운로드 및 업로드합니다.
  • 플러그 인을 사용하지 않고 멀티미디어 콘텐츠 스트리밍을 다운로드합니다.
  • XMLHttpRequest 작업 상태를 더 잘 관찰합니다.
  • 다른 브라우저와의 상호 운용성을 개선합니다.

이러한 변경 내용은 다음 섹션에서 자세히 설명합니다.

이진 개체 업로드 및 다운로드

Internet Explorer 10에서는 XMLHttpRequest를 확장하여 이진 데이터를 지원합니다. 부분적으로 이 작업을 위해 파일 API 사양BLOB 인터페이스 지원을 추가합니다.

XMLHttpRequest 개체의 responseType 속성을 "blob"로 설정하면 요청과 관련된 데이터가 이진 데이터로 처리됩니다. 이 경우 다운로드 요청(예: GET)의 응답 속성 값에 영향을 줍니다.

다음 예제는 XMLHttpRequest를 사용하여 이미지를 BLOB 개체로 다운로드한 다음 그 결과를 웹 페이지의 이미지 요소에 할당하는 방법을 보여 줍니다.

JavaScript
var req = new XMLHttpReqest();
xhr.open("GET", "download?name=" + name, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function () {
  if (xhr.readyState == xhr.DONE) {
    var blob = xhr.reponse;
    var image = document.getElementById("my-image");
    image.addEventListener("load", function (evt) {
      URL.revokeObjectURL(evt.target.src);
    }
    image.src = URL.createObjectURL(blob);
  }
}
xhr.send();

다운로드 요청에 대해 responseType 속성을 "ms-stream"으로 설정하면 다음 예제와 같이 콘텐츠를 즉석에서 처리할 수 있습니다.

JavaScript
var req = new XMLHttpReqest();
xhr.open("GET", "download?name=" + name, true);
xhr.responseType = "ms-stream";
xhr.onreadystatechange = function () {
  if (xhr.readyState == xhr.LOADING) {
    var stream = xhr.reponse;
    var video = document.getElementById("my-video");
    video.addEventListener("loadeddata", function (evt) {
      URL.revokeObjectURL(evt.target.src);
    }
    video.src = URL.createObjectURL(stream);
  }
}
xhr.send();

Comet 스트리밍 지원

Internet Explorer 10에서는 다음 예제와 같이 XMLHttpRequest 요청에 대한 응답을 로드하는 동안 responseText 속성을 읽을 수 있도록 하여 multipart HTTP 스트리밍(Comet 스트리밍이라고도 함)을 지원합니다.

JavaScript
xhr.open("GET", url);
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
  if (this.readyState >= 3 && this.status == 200) {
    var content = this.responseText;
    handleContent(content);
  }
}
xhr.send();

이전 Windows Internet Explorer 버전에서는 readyState 속성이 done으로 설정된 경우에만 responseText 속성을 읽을 수 있습니다.

responseText 속성은 현재까지 읽은 응답의 전체 값을 반환합니다. 응답이 수신될 때 개별 응답 패킷을 처리하려면 다음 예제와 같이 progress 이벤트(다음 섹션에 설명됨)를 사용하거나 각 readyStateChange 이벤트 반복의 responseText 길이를 추적할 수 있습니다.

JavaScript
xhr.open("GET", url);
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
  if (typeof this.index == "undefined")
    this.index = 0;
    
  if (this.readyState >= 3 && this.status == 200) {
    var content = this.responseText;
    handleContent( content.substring(this.index) )
    this.index = content.length;
  }
}
xhr.send();

고급 이벤트 지원

Internet Explorer 10에서는 XMLHttpRequest 개체를 확장하여 XMLHttpRequest 수준 2 사양에 지정된 다음 이벤트를 지원합니다.

이벤트설명

loadstart

요청이 시작될 때 발생합니다.

progress

요청이 데이터를 보내거나 받는 동안 서버에서 정의된 간격으로 발생합니다.

abort

요청이 취소될 때(예: abort() 메서드가 호출될 때) 발생합니다.

error

요청이 실패할 때 발생합니다.

load

요청이 성공적으로 완료될 때 발생합니다.

timeout

작성자가 지정한 기간이 경과할 때 발생합니다.

loadend

성공 여부에 관계없이 요청이 완료될 때 발생합니다.

 

XMLHttpRequest 개체의 이벤트 처리는 다음 예제와 같이 DOM 이벤트 수준 3 사양 및 진행률 이벤트 사양에 지정된 모델을 따릅니다.

JavaScript
var xhr = new XMLHttpRequest();
var url = "some-url";

xhr.timeout = 5000;
xhr.addEventListener("timeout", handleTimeout(evt), false);

xhr.onprogress = function(evt) {
  handleEvent("data: " + this.responseText);
  // Calculate progress 
  var str = "";
  if (evt.lengthComputable) {
    var percent = 100 * evt.loaded / evt.total;
    str = percent + "%. Current total size: " + this.responseText.length);
  } else {
    str = "Progress unknown. Current total size: " + this.responseText.length;
  }
  updateProgress(str);
}
xhr.open("GET", url);
xhr.send();

XMLHttpRequest에 대한 CORS(Cross-Origin Resource Sharing)

Internet Explorer 10에서는 XMLHttpRequest(XHR) 개체와 관련하여 CORS(Cross-Origin Resource Sharing)를 새롭게 지원합니다. CORS(Cross-Origin Resource Sharing) 사양에 정의된 CORS는 HTTP 헤더를 사용하여 대개 동일한 사이트 출처 정책으로 제한되는 도메인 간 웹 요청을 가능하게 합니다.

기본적으로 동일한 사이트 출처 정책은 웹 사이트가 다른 도메인에 있는 서버의 리소스를 요청하지 못하도록 합니다. 그러나 XMLHttpRequest(XHR) 요청에 대한 CORS를 지원하는 브라우저는 적절한 관리자가 해당 요청을 허용하도록 선택할 경우 다른 도메인의 리소스에 액세스할 수 있습니다.

웹 페이지가 XHR request를 수행하면 Internet Explorer에서 원본 헤더를 대상 서버로 보냅니다. 헤더에는 요청의 프로토콜 체계(http:// 또는 https://) 및 요청하는 웹 페이지의 호스트 이름이 포함됩니다. 대상 서버는 요청을 승인할 경우 Access-Control-Allow-Origin 헤더를 반환하며 요청을 처리할 수 있습니다.

이제 XMLHttpRequest 개체가 XHR 요청에 권한 부여 메커니즘을 포함할 수 있게 하는 withCredentials 속성을 지원합니다. 자세한 내용은 XMLHttpRequest 수준 2 사양을 참조하세요.

다음 예제와 같이 withCredentials 속성을 사용하여 CORS 지원을 검색할 수 있습니다.

JavaScript
var url = "http://contoso.com/services/"
if( window.XMLHttpRequest ) {
  var oReq = new XMLHttpRequest();
  if( oReq.withCredentials == undefined ) {
    oReq.open("GET", url, true);
    oReq.onload = handleResponse();
    oReq.send( null );
  } else {
  // CORS not support.  Handle fallback
  }
} else { 
  // XMLHttpRequest not supported; handle fallback
}

CORS의 실습 데모는 IE 테스트 드라이브실습: 사이트 간 업로드(영문)를 참조하세요.

관련 항목

DOM(문서 개체 모델)
개발자용 Internet Explorer 10 가이드


'Language > JAVASCRIPT' 카테고리의 다른 글

prototypejs  (0) 2013.11.13
마우스 커서 포지션 이동  (0) 2013.05.22
XMLHttpRequest Level 2  (0) 2013.04.29
XMLHttpRequest  (0) 2013.04.29
자바스크립트  (0) 2013.02.22
:

XMLHttpRequest Level 2

Language/JAVASCRIPT 2013. 4. 29. 18:09

http://www.w3.org/TR/XMLHttpRequest2/#event-xhr-load


W3C

XMLHttpRequest Level 2

W3C Working Draft 17 January 2012

This Version:
http://www.w3.org/TR/2012/WD-XMLHttpRequest-20120117/
Latest Version:
http://www.w3.org/TR/XMLHttpRequest/
Latest Editor Draft:
http://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html
Previous Versions:
http://www.w3.org/TR/2011/WD-XMLHttpRequest2-20110816/
http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/
http://www.w3.org/TR/2009/WD-XMLHttpRequest2-20090820/
http://www.w3.org/TR/2008/WD-XMLHttpRequest2-20080930/
http://www.w3.org/TR/2008/WD-XMLHttpRequest2-20080225/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20071026/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070618/
http://www.w3.org/TR/2007/WD-XMLHttpRequest-20070227/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060927/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060619/
http://www.w3.org/TR/2006/WD-XMLHttpRequest-20060405/
Editor:
Anne van Kesteren (Opera Software ASA) <annevk@opera.com>

Abstract

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

Status of this Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 17 January 2012 W3C Working Draft of XMLHttpRequest Level 2. Please send comments to public-webapps@w3.org (archived) with [XHR] at the start of the subject line.

This document is produced by the Web Applications (WebApps) Working Group. The WebApps Working Group is part of the Rich Web Clients Activity in the W3C Interaction Domain.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document supersedes XMLHttpRequest 1.

Table of Contents

  1. 1 Introduction
    1. 1.1 Specification history
  2. 2 Conformance
    1. 2.1 Dependencies
    2. 2.2 Extensibility
  3. 3 Terminology
  4. 4 Interface XMLHttpRequest
    1. 4.1 Origin and base URL
    2. 4.2 Task sources
    3. 4.3 Constructors
    4. 4.4 Garbage collection
    5. 4.5 Event handlers
    6. 4.6 States
    7. 4.7 Request
      1. 4.7.1 The open() method
      2. 4.7.2 The setRequestHeader() method
      3. 4.7.3 The timeout attribute
      4. 4.7.4 The withCredentials attribute
      5. 4.7.5 The upload attribute
      6. 4.7.6 The send() method
      7. 4.7.7 Infrastructure for the send() method
      8. 4.7.8 The abort() method
    8. 4.8 Response
      1. 4.8.1 The status attribute
      2. 4.8.2 The statusText attribute
      3. 4.8.3 The getResponseHeader() method
      4. 4.8.4 The getAllResponseHeaders() method
      5. 4.8.5 Response entity body
      6. 4.8.6 The overrideMimeType() method
      7. 4.8.7 The responseType attribute
      8. 4.8.8 The response attribute
      9. 4.8.9 The responseText attribute
      10. 4.8.10 The responseXML attribute
    9. 4.9 Events summary
  5. 5 Interface FormData
    1. 5.1 Constructors
    2. 5.2 The append() method
  6. References
    1. Normative references
  7. Acknowledgments

1 Introduction

This section is non-normative.

The XMLHttpRequest object is the ECMAScript HTTP API. [ECMASCRIPT]

The name of the object is XMLHttpRequest for compatibility with the Web, though each component of this name is potentially misleading. First, the object supports any text based format, including XML. Second, it can be used to make requests over both HTTP and HTTPS (some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification). Finally, it supports "requests" in a broad sense of the term as it pertains to HTTP; namely all activity involved with HTTP requests or responses for the defined HTTP methods.

Some simple code to do something with data from an XML document fetched over the network:

function processData(data) {
  // taking care of data
}

function handler() {
  if(this.readyState == this.DONE) {
    if(this.status == 200 &&
       this.responseXML != null &&
       this.responseXML.getElementById('test').textContent) {
      // success!
      processData(this.responseXML.getElementById('test').textContent);
      return;
    }
    // something went wrong
    processData(null);
  }
}

var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();

If you just want to log a message to the server:

function log(message) {
  var client = new XMLHttpRequest();
  client.open("POST", "/log");
  client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
  client.send(message);
}

Or if you want to check the status of a document on the server:

function fetchStatus(address) {
  var client = new XMLHttpRequest();
  client.onreadystatechange = function() {
    // in case of network errors this might not give reliable results
    if(this.readyState == this.DONE)
      returnStatus(this.status);
  }
  client.open("HEAD", address);
  client.send();
}

1.1 Specification history

The XMLHttpRequest object was initially defined as part of the WHATWG's HTML effort. (Long after Microsoft shipped an implementation.) It moved to the W3C in 2006. Extensions (e.g. progress events and cross-origin requests) to XMLHttpRequest were developed in a separate draft (XMLHttpRequest Level 2) until end of 2011, at which point the two drafts were merged and XMLHttpRequest became a single entity again from a standards perspective.

Historical discussion can be found in the following mailing list archives:

2 Conformance

All diagrams, examples, and notes in this specification are non-normative, as are all sections explicitly marked non-normative. Everything else in this specification is normative.

The key words "MUST", "MUST NOT", "REQUIRED", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in the normative parts of this specification are to be interpreted as described in RFC2119. For readability, these words do not appear in all uppercase letters in this specification. [RFC2119]

2.1 Dependencies

This specification relies on several underlying specifications.

Cross-Origin Resource Sharing

A conforming user agent must support the algorithms of the Cross-Origin Resource Sharing specification. [CORS]

DOM4

A conforming user agent must support at least the subset of the functionality defined in DOM4 that this specification relies upon, such as various exceptions and EventTarget. [DOM]

File API

A conforming user agent must support at least the subset of the functionality defined in File API that this specification relies upon, such as the Blob and File interfaces. [FILEAPI]

HTML

A conforming user agent must support at least the subset of the functionality defined in HTML that this specification relies upon, such as the basics of the Window object and serializing a Document object. [HTML]

HTTP

A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [HTTP]

Progress Events

A conforming user agent must support the Progress Events specification. [PROGRESSEVENTS]

Typed Array

A conforming user agent must support the ArrayBuffer object. [TYPEDARRAY]

Web IDL

A conforming user agent must also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WEBIDL]

XML

A conforming user agent must be a conforming XML processor that reports violations of namespace well-formedness. [XML] [XMLNS]

2.2 Extensibility

User agents, Working Groups, and other interested parties are strongly encouraged to discuss new features on a relevant public forum, preferably public-webapps@w3.org. If this is for some reason not possible prefix the extension in some way. E.g. if company Foo wants to add a proprietary method bar() it could be named fooBar() to prevent clashes with a potential non-proprietary method bar().

3 Terminology

The term user credentials for the purposes of this specification means cookies, HTTP authentication, and client-side SSL certificates. Specifically it does not refer to proxy authentication or the Origin header. [COOKIES]

To deflate a DOMString into a byte sequence means to create a sequence of bytes such that the nth byte of the sequence is equal to the low-order byte of the nth code point in the original DOMString.

To inflate a byte sequence into a DOMString means to create a DOMString such that the nth code point has 0x00 as the high-order byte and the nth byte of the byte sequence as the low-order byte.

4 Interface XMLHttpRequest

[NoInterfaceObject]
interface XMLHttpRequestEventTarget : EventTarget {
  // event handlers
  [TreatNonCallableAsNull] attribute Function? onloadstart;
  [TreatNonCallableAsNull] attribute Function? onprogress;
  [TreatNonCallableAsNull] attribute Function? onabort;
  [TreatNonCallableAsNull] attribute Function? onerror;
  [TreatNonCallableAsNull] attribute Function? onload;
  [TreatNonCallableAsNull] attribute Function? ontimeout;
  [TreatNonCallableAsNull] attribute Function? onloadend;
};

interface XMLHttpRequestUpload : XMLHttpRequestEventTarget {

};

enum XMLHttpRequestResponseType {
  "",
  "arraybuffer",
  "blob",
  "document",
  "json",
  "text"
}

[Constructor]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
  // event handler
  [TreatNonCallableAsNull] attribute Function? onreadystatechange;

  // states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;
  readonly attribute unsigned short readyState;

  // request
  void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password);
  void setRequestHeader(DOMString header, DOMString value);
           attribute unsigned long timeout;
           attribute boolean withCredentials;
  readonly attribute XMLHttpRequestUpload upload;
  void send();
  void send(ArrayBuffer data);
  void send(Blob data);
  void send(Document data);
  void send(DOMString? data);
  void send(FormData data);
  void abort();

  // response
  readonly attribute unsigned short status;
  readonly attribute DOMString statusText;
  DOMString getResponseHeader(DOMString header);
  DOMString getAllResponseHeaders();
  void overrideMimeType(DOMString mime);
           attribute XMLHttpRequestResponseType responseType;
  readonly attribute any response;
  readonly attribute DOMString responseText;
  readonly attribute Document responseXML;
};

[Constructor]
interface AnonXMLHttpRequest : XMLHttpRequest {
};

4.1 Origin and base URL

Each XMLHttpRequest object has an associated XMLHttpRequest origin and an XMLHttpRequest base URL.

This specification defines their values when the global object is represented by the Window object. When the XMLHttpRequest object is used in other contexts their values will have to be defined as appropriate for that context. That is considered to be out of scope for this specification.

In environments where the global object is represented by the Window object the XMLHttpRequest object has an associated XMLHttpRequest document which is the document associated with the Window object for which the XMLHttpRequest interface object was created.

The XMLHttpRequest document is used to determine the XMLHttpRequest origin and XMLHttpRequest base URL at a later stage.

4.2 Task sources

Each XMLHttpRequest object has its own task source. Namely, the XMLHttpRequest task source.

4.3 Constructors

The XMLHttpRequest object has an associated anonymous flag. If the anonymous flag is set, user credentials and the XMLHttpRequest origin are not exposed when fetching resources. It can only be set to true by using the AnonXMLHttpRequest() constructor.

client = new XMLHttpRequest()
Returns a new XMLHttpRequest object.
client = new AnonXMLHttpRequest()
Returns a new AnonXMLHttpRequest object that has the anonymous flag set.

The XMLHttpRequest() constructor must return a new XMLHttpRequest object.

The AnonXMLHttpRequest() constructor must return a new AnonXMLHttpRequest object with its anonymous flag set.

4.4 Garbage collection

An XMLHttpRequest object must not be garbage collected if its state is OPENED and the send() flag is set, its state is HEADERS_RECEIVED, or its state is LOADING, and one of the following is true:

If an XMLHttpRequest object is garbage collected while its connection is still open, the user agent must cancel any instance of the fetch algorithm opened by this object, discarding any tasks queued for them, and discarding any further data received from the network for them.

4.5 Event handlers

The following are the event handlers (and their corresponding event handler event types) that must be supported on objects implementing an interface that inherits from XMLHttpRequestEventTarget as attributes:

event handler event handler event type
onloadstart loadstart
onprogress progress
onabort abort
onerror error
onload load
ontimeout timeout
onloadend loadend

The following is the event handler (and its corresponding event handler event type) that must be supported as attribute solely by the XMLHttpRequest object:

event handler event handler event type
onreadystatechange readystatechange

4.6 States

client . readyState

Returns the current state.

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

The send() flag indicates that the send() method has been invoked. It is initially unset and is used during the OPENED state.

The error flag indicates some type of network error or request abortion. It is initially unset and is used during the DONE state.

4.7 Request

The XMLHttpRequest object holds the following request metadata variables:

synchronous flag
Set when fetching is done synchronously. Initially unset.
request method
The HTTP method used in the request.
request URL
The resolved URL used in the request.
request username
The username used in the request or null if there is no username.
request password
The password used in the request or null if there is no password.
author request headers
A list consisting of HTTP header name/value pairs to be used in the request.
request entity body
The entity body used in the request or null if there is no entity body.
upload complete flag
Set when no more events are to be dispatched on the XMLHttpRequestUpload object. Initially unset.
upload events flag
Set when event listeners are registered on the XMLHttpRequestUpload object to determine whether a preflight request is needed. Initially unset.

The XMLHttpRequest object also has an associated XMLHttpRequestUpload object.

4.7.1 The open() method

client . open(method, url, async, user, password)

Sets the request method, request URL, synchronous flag, request username, and request password.

Throws a "SyntaxError" exception if one of the following is true:

  • method is not a valid HTTP method.
  • url cannot be resolved.
  • url contains the "user:password" format in the userinfo production.

Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.

Throws an "InvalidAccessError" exception if one of the following is true:

The open(method, url, async, user, password) method must run these steps (unless otherwise indicated):

  1. If there is an associated XMLHttpRequest document run these substeps:

    1. If the XMLHttpRequest document is not fully active, throw an "InvalidStateError" exception and terminate the overall set of steps.

    2. Let XMLHttpRequest base URL be the document base URL of the XMLHttpRequest document.

    3. Let XMLHttpRequest origin be the origin of the XMLHttpRequest document and let it be a globally unique identifier if the anonymous flag is set.

  2. If any code point in method is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating method it does not match the Method token production, throw a "SyntaxError" exception and terminate these steps. Otherwise let method be the result of deflating method.

  3. If method is a case-insensitive match for CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE, or TRACK subtract 0x20 from each byte in the range 0x61 (ASCII a) to 0x7A (ASCII z).

    If it does not match any of the above, it is passed through literally, including in the final request.

  4. If method is a case-sensitive match for CONNECT, TRACE, or TRACK, throw a "SecurityError" exception and terminate these steps.

    Allowing these methods poses a security risk. [HTTPVERBSEC]

  5. Let url be a URL with character encoding UTF-8.

  6. Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError" exception and terminate these steps.

  7. Drop <fragment> from url.

  8. If the "user:password" format in the userinfo production is not supported for the relevant <scheme> and url contains this format, throw a "SyntaxError" and terminate these steps.

  9. If url contains the "user:password" format let temp user be the user part and temp password be the password part.

  10. If url just contains the "user" format let temp user be the user part.

  11. Let async be the value of the async argument or true if it was omitted.

    If async is false, there is an associated XMLHttpRequest document and either the timeout attribute value is not zero, the withCredentials attribute value is true, or the responseType attribute value is not the empty string, throw an "InvalidAccessError" exception and terminate these steps.

  12. If the user argument was not omitted follow these sub steps:

    1. If user is not null and the origin of url is not same origin with the XMLHttpRequest origin, throw an "InvalidAccessError" exception and terminate the overall set of steps.

    2. Let temp user be user.

    These steps override anything that may have been set by the url argument.

  13. If the password argument was not omitted follow these sub steps:

    1. If password is not null and the origin of url is not same origin with the XMLHttpRequest origin, throw an "InvalidAccessError" exception and terminate the overall set of steps.

    2. Let temp password be password.

    These steps override anything that may have been set by the url argument.

  14. Terminate the abort() algorithm.

  15. Terminate the send() algorithm.

  16. The user agent should cancel any network activity for which the object is responsible.

  17. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove them.

  18. Set variables associated with the object as follows:

  19. Change the state to OPENED.

  20. Fire an event named readystatechange.

4.7.2 The setRequestHeader() method

client . setRequestHeader(header, value)

Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value.

Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.

Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value.

As indicated in the algorithm below certain headers cannot be set and are left up to the user agent. In addition there are certain other headers the user agent will take control of if they are not set by the author as indicated at the end of the send() method section.

For non same origin requests using the HTTP GET method a preflight request is made when headers other than Accept and Accept-Language are set.

The setRequestHeader(header, value) method must run these steps:

  1. If the state is not OPENED, throw an "InvalidStateError" exception and terminate these steps.

  2. If the send() flag is set, throw an "InvalidStateError" exception and terminate these steps.

  3. If any code point in header is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating header it does not match the field-name production, throw a "SyntaxError" exception and terminate these steps. Otherwise let header be the result of deflating header.

  4. If any code point in value is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating value it does not match the field-value production, throw a "SyntaxError" exception and terminate these steps. Otherwise let value be the result of deflating value.

    The empty string is legal and represents the empty header value.

  5. Terminate these steps if header is a case-insensitive match for one of the following headers:

    • Accept-Charset
    • Accept-Encoding
    • Access-Control-Request-Headers
    • Access-Control-Request-Method
    • Connection
    • Content-Length
    • Cookie
    • Cookie2
    • Content-Transfer-Encoding
    • Date
    • Expect
    • Host
    • Keep-Alive
    • Origin
    • Referer
    • TE
    • Trailer
    • Transfer-Encoding
    • Upgrade
    • User-Agent
    • Via

    … or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).

    The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent. Header names starting with Sec- are not allowed to be set to allow new headers to be minted that are guaranteed not to come from XMLHttpRequest.

  6. If header is not in the author request headers list append header with its associated value to the list and terminate these steps.

  7. If header is in the author request headers list either use multiple headers, combine the values or use a combination of those (section 4.2, RFC 2616). [HTTP]

See also the send() method regarding user agent header handling for caching, authentication, proxies, and cookies.

Some simple code demonstrating what happens when setting the same header twice:

// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');
client.send();

// …results in the following header being sent:
X-Test: one, two

4.7.3 The timeout attribute

client . timeout

The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.

When set: throws an "InvalidAccessError" exception if the synchronous flag is set when there is an associated XMLHttpRequest document.

The timeout attribute must return its value. Initially its value must be zero.

Setting the timeout attribute must run these steps:

  1. If there is an associated XMLHttpRequest document and the synchronous flag is set, throw an "InvalidAccessError" exception and terminate these steps.

  2. Set its value to the new value.

This implies that the timeout attribute can be set while fetching is in progress. If that occurs it will still be measured relative to the start of fetching.

4.7.4 The withCredentials attribute

client . withCredentials

True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false.

When set: throws an "InvalidStateError" exception if the state is not UNSENT or OPENED, or if the send() flag is set.

When set: throws an "InvalidAccessError" exception if either the synchronous flag is set when there is an associated XMLHttpRequest document or if the anonymous flag is set.

The withCredentials attribute must return its value. Initially its value must be false.

Setting the withCredentials attribute must run these steps:

  1. If the state is not UNSENT or OPENED, throw an "InvalidStateError" exception and terminate these steps.

  2. If the send() flag is set, throw an "InvalidStateError" exception and terminate these steps.

  3. If the anonymous flag is set, throw an "InvalidAccessError" exception and terminate these steps.

  4. If there is an associated XMLHttpRequest document and the synchronous flag is set, throw an "InvalidAccessError" exception and terminate these steps.

  5. Set the withCredentials attribute's value to the given value.

The withCredentials attribute has no effect when fetching same-origin resources.

4.7.5 The upload attribute

client . upload

Returns the associated XMLHttpRequestUpload object.

The upload attribute must return the associated XMLHttpRequestUpload object.

4.7.6 The send() method

client . send(data)

Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD.

Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.

The send(data) method must run these steps (unless otherwise noted). This algorithm can be terminated by invoking the open() or abort() method. When it is terminated the user agent must terminate the algorithm after finishing the step it is on.

The send() algorithm can only be terminated if the synchronous flag is unset and only after the method call has returned.

  1. If the state is not OPENED, throw an "InvalidStateError" exception and terminate these steps.

  2. If the send() flag is set, throw an "InvalidStateError" exception and terminate these steps.

  3. If the request method is a case-sensitive match for GET or HEAD act as if data is null.

    If the data argument has been omitted or is null, do not include a request entity body and go to the next step.

    Otherwise, let encoding be null, mime type be null, and then follow these rules:

    If data is a ArrayBuffer

    Let the request entity body be the raw data represented by data.

    If data is a Blob

    If the object's type attribute is not the empty string let mime type be its value.

    Let the request entity body be the raw data represented by data.

    If data is a Document

    Let encoding be the preferred MIME name of the character encoding of data. If encoding is UTF-16 change it to UTF-8.

    Let mime type be "application/xml" or "text/html" if Document is an HTML document, followed by ";charset=", followed by encoding.

    Let the request entity body be the result of getting the innerHTML attribute on data converted to Unicode and encoded as encoding. Re-throw any exception this throws.

    In particular, if the document cannot be serialized an "InvalidStateError" exception is thrown.

    Subsequent changes to the Document have no effect on what is transferred.

    If data is a string

    Let encoding be UTF-8.

    Let mime type be "text/plain;charset=UTF-8".

    Let the request entity body be data converted to Unicode and encoded as UTF-8.

    If data is a FormData

    Let the request entity body be the result of running the multipart/form-data encoding algorithm with data as form data set and with UTF-8 as the explicit character encoding.

    Let mime type be the concatenation of "multipart/form-data;", a U+0020 SPACE character, "boundary=", and the multipart/form-data boundary string generated by the multipart/form-data encoding algorithm.

    If a Content-Type header is in author request headers and its value is a valid MIME type that has a charset parameter whose value is not a case-insensitive match for encoding, and encoding is not null, set all the charset parameters of that Content-Type header to encoding.

    If no Content-Type header is in author request headers and mime type is not null, append a Content-Type header with value mime type to author request headers.

  4. If the synchronous flag is set, release the storage mutex.

  5. If the synchronous flag is unset and one or more event listeners are registered on the XMLHttpRequestUpload object, set the upload events flag.

  6. Unset the error flag.

  7. Set the upload complete flag if there is no request entity body or if the request entity body is empty.

  8. If the synchronous flag is unset, run these substeps:

    1. Set the send() flag.

    2. Fire an event named readystatechange.

      The state does not change. The event is dispatched for historical reasons.

    3. Fire a progress event named loadstart.

    4. If the upload complete flag is unset, fire a progress event named loadstart on the XMLHttpRequestUpload object.

    5. Return the send() method call, but continue running the steps in this algorithm.

  9. If the XMLHttpRequest origin and the request URL are same origin

    These are the same-origin request steps.

    Fetch the request URL from origin XMLHttpRequest origin, with the synchronous flag set if the synchronous flag is set, using HTTP method request method, user request username (if non-null) and password request password (if non-null), taking into account the request entity body, list of author request headers and the rules listed at the end of this section.

    If the synchronous flag is set

    While making the request also follow the same-origin request event rules.

    The send() method call will now be returned by virtue of this algorithm ending.

    If the synchronous flag is unset

    Make upload progress notifications.

    Make progress notifications.

    While processing the request, as data becomes available and when the user interferes with the request, queue tasks to update the response entity body and follow the same-origin request event rules.

    Otherwise

    These are the cross-origin request steps.

    Make a cross-origin request, passing these as parameters:

    request URL
    The request URL.
    request method
    The request method.
    author request headers
    The list of author request headers.
    request entity body
    The request entity body.
    source origin
    The XMLHttpRequest origin.
    credentials flag
    The withCredentials attribute's value.
    force preflight flag
    True if the upload events flag is set, or false otherwise.

    Request username and request password are always ignored as part of a cross-origin request; including them would allow a site to perform a distributed password search. However, user agents will include user credentials in the request (if the user has any and if withCredentials is true).

    If the synchronous flag is set

    While making the request also follow the cross-origin request event rules.

    The send() method call will now be returned by virtue of this algorithm ending.

    If the synchronous flag is unset

    While processing the request, as data becomes available and when the end user interferes with the request, queue tasks to update the response entity body and follow the cross-origin request event rules.


If the user agent allows the end user to configure a proxy it should modify the request appropriately; i.e., connect to the proxy host instead of the origin server, modify the Request-Line and send Proxy-Authorization headers as specified.


If the user agent supports HTTP Authentication and Authorization is not in the list of author request headers, it should consider requests originating from the XMLHttpRequest object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorized requests appropriately.

If authentication fails, XMLHttpRequest origin and the request URL are same origin, Authorization is not in the list of author request headers, request username is null, and request password is null, user agents should prompt the end user for their username and password.

Otherwise, if authentication fails, user agents must not prompt the end user for their username and password. [HTTPAUTH]

End users are not prompted for various cases so that authors can implement their own user interface.


If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable. [COOKIES]


If the user agent implements a HTTP cache it should respect Cache-Control headers in author request headers (e.g. Cache-Control: no-cache bypasses the cache). It must not send Cache-Control or Pragma request headers automatically unless the end user explicitly requests such behavior (e.g. by reloading the page).

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow author request headers to override automatic cache validation (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through. [HTTP]


If the user agent implements server-driven content-negotiation it must follow these constraints for the Accept and Accept-Language request headers:

Responses must have the content-encodings automatically decoded. [HTTP]


Besides the author request headers, user agents should not include additional request headers other than those mentioned above or other than those authors are not allowed to set using setRequestHeader(). This ensures that authors have a predictable API.

4.7.7 Infrastructure for the send() method

The same-origin request event rules are as follows:

If the response has an HTTP status code of 301, 302, 303, or 307

If the redirect violates infinite loop precautions this is a network error.

Otherwise, run these steps:

  1. Set the request URL to the URL conveyed by the Location header.

  2. If the XMLHttpRequest origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.

  3. Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.

HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.

If the end user cancels the request

This is an abort error.

If there is a network error

In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error. Do not request any kind of end user interaction.

This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.

If timeout is not 0 and since the request started the amount of milliseconds specified by timeout has passed

This is a timeout error.

Once all HTTP headers have been received, the synchronous flag is unset, and the HTTP status code of the response is not 301, 302, 303, or 307

Switch to the HEADERS_RECEIVED state.

Once the first byte (or more) of the response entity body has been received and the synchronous flag is unset
If there is no response entity body and the synchronous flag is unset

Switch to the LOADING state.

Once the whole response entity body has been received
If there is no response entity body and the state is LOADING
If there is no response entity body and the synchronous flag is set

Switch to the DONE state.


The cross-origin request event rules are as follows:

If the cross-origin request status is preflight complete and the synchronous flag is unset

Make upload progress notifications.

If the cross-origin request status is network error

This is a network error.

If the cross-origin request status is abort error

This is an abort error.

If timeout is not 0 and since the request started the amount of milliseconds specified by timeout has passed

This is a timeout error.

Once all HTTP headers have been received, the cross-origin request status is success, and the synchronous flag is unset

Switch to the HEADERS_RECEIVED state.

Make progress notifications.

Once the first byte (or more) of the response entity body has been received, the cross-origin request status is success, and the synchronous flag is unset
If there is no response entity body, the cross-origin request status is success, and the synchronous flag is unset

Switch to the LOADING state.

Once the whole response entity body has been received and the cross-origin request status is success
If there is no response entity body, the cross-origin request status is success, and the state is LOADING
If there is no response entity body, the cross-origin request status is success, and the synchronous flag is set

Switch to the DONE state.


When something is said to be a network error run the request error steps for exception "NetworkError" and event error.

When something is said to be an abort error run the request error steps for exception "AbortError" and event abort.

When something is said to be an timeout error run the request error steps for exception "TimeoutError" and event timeout.

When something is said to be a request error for exception exception and event event run these steps:

  1. The user agent should cancel any network activity for which the object is responsible.

  2. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove them.

  3. Set the the error flag.

  4. Change the state to DONE.

  5. If the synchronous flag is set, throw an exception exception and terminate the overall set of steps.

  6. Fire an event named readystatechange.

    At this point it is clear that the synchronous flag is unset.

  7. If the upload complete flag is unset, follow these substeps:

    1. Set the upload complete flag.

    2. Fire a progress event named event on the XMLHttpRequestUpload object.

    3. Fire a progress event named loadend on the XMLHttpRequestUpload object.

  8. Fire a progress event named event.

  9. Fire a progress event named loadend.


When it is said to switch to the HEADERS_RECEIVED state run these steps:

  1. Change the state to HEADERS_RECEIVED.

  2. Fire an event named readystatechange.

When it is said to switch to the LOADING state run these steps:

  1. Change the state to LOADING.

  2. Fire an event named readystatechange.

When it is said to switch to the DONE state run these steps:

  1. If the synchronous flag is set, update the response entity body.

  2. Unset the synchronous flag.

  3. Change the state to DONE.

  4. Fire an event named readystatechange.

  5. Fire a progress event named load.

  6. Fire a progress event named loadend.


When it is said to make progress notifications, while the download is progressing, queue a task to fire a progress event named progress about every 50ms or for every byte received, whichever is least frequent.


When it is said to make upload progress notifications run these steps:

4.7.8 The abort() method

client . abort()
Cancels any network activity.

The abort() method must run these steps (unless otherwise noted). This algorithm can be terminated by invoking the open() method. When it is terminated the user agent must terminate the algorithm after finishing the step it is on.

The abort() algorithm can only be terminated by invoking open() from an event handler.

  1. Terminate the send() algorithm.

  2. The user agent should cancel any network activity for which the object is responsible.

  3. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove them.

  4. Set the error flag.

  5. Unset the synchronous flag.

  6. If the state is UNSENT, OPENED with the send() flag being unset, or DONE go to the next step.

    Otherwise run these substeps:

    1. Change the state to DONE.

    2. Unset the send() flag.

    3. Fire an event named readystatechange.

    4. Fire a progress event named abort.

    5. Fire a progress event named loadend.

    6. If the upload complete flag is false run these substeps:

      1. Set the upload complete flag to true.

      2. Fire a progress event named abort on the XMLHttpRequestUpload object.

      3. Fire a progress event named loadend on the XMLHttpRequestUpload object.

  7. Change the state to UNSENT.

    No readystatechange event is dispatched.

4.8 Response

4.8.1 The status attribute

client . status

Returns the HTTP status code.

The status attribute must return the result of running these steps:

  1. If the state is UNSENT or OPENED, return 0 and terminate these steps.

  2. If the error flag is set, return 0 and terminate these steps.

  3. Return the HTTP status code.

4.8.2 The statusText attribute

client . statusText

Returns the HTTP status text.

The statusText attribute must return the result of running these steps:

  1. If the state is UNSENT or OPENED, return the empty string and terminate these steps.

  2. If the error flag is set, return the empty string and terminate these steps.

  3. Return the HTTP status text.

4.8.3 The getResponseHeader() method

client . getResponseHeader(header)

Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2.

The getResponseHeader(header) method must run these steps:

  1. If the state is UNSENT or OPENED, return null and terminate these steps.

  2. If the error flag is set, return null and terminate these steps.

  3. If any code point in header is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS, return null and terminate these steps.

  4. Let header be the result of deflating header.

  5. If header is a case-insensitive match for Set-Cookie or Set-Cookie2, return null and terminate these steps.

  6. If header is a case-insensitive match for multiple HTTP response headers, return the inflated values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair and terminate these steps.

  7. If header is a case-insensitive match for a single HTTP response header, return the inflated value of that header and terminate these steps.

  8. Return null.

The Cross-Origin Resource Sharing specification filters the headers that are exposed by getResponseHeader() for non same-origin requests. [CORS]

For the following script:

var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
  if(this.readyState == 2) {
    print(client.getResponseHeader("Content-Type"));
  }
}

The print() function will get to process something like:

text/plain; charset=UTF-8

4.8.4 The getAllResponseHeaders() method

client . getAllResponseHeaders()

Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.

The getAllResponseHeaders() method must run these steps:

  1. If the state is UNSENT or OPENED, return the empty string and terminate these steps.

  2. If the error flag is set, return the empty string and terminate these steps.

  3. Return all the HTTP headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, inflated, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

The Cross-Origin Resource Sharing specification filters the headers that are exposed by getAllResponseHeaders() for non same-origin requests. [CORS]

For the following script:

var client = new XMLHttpRequest();
client.open("GET", "narwhals-too.txt", true);
client.send();
client.onreadystatechange = function() {
  if(this.readyState == 2) {
    print(this.getAllResponseHeaders());
  }
}

The print() function will get to process something like:

Date: Sun, 24 Oct 2004 04:58:38 GMT
Server: Apache/1.3.31 (Unix)
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8

4.8.5 Response entity body

The response MIME type is the MIME type the Content-Type header contains excluding any parameters, or null if the response header can not be parsed or was omitted. The override MIME type is initially null and can get a value if overrideMimeType() is invoked. Final MIME type is the override MIME type unless that is null in which case it is the response MIME type.

The response charset is the value of the charset parameter of the Content-Type header or null if there was no charset parameter or the header could not be parsed or was omitted. The override charset is initially null and can get a value if overrideMimeType() is invoked. Final charset is the override charset unless that is null in which case it is the response charset.


The response entity body is the fragment of the entity body of the response received so far (LOADING) or the complete entity body of the response (DONE). If the response does not have an entity body, the response entity body is null.

The response entity body is updated as part of the send() algorithm.


The arraybuffer response entity body is an ArrayBuffer representing the response entity body. If the arraybuffer response entity body has no value assigned to it let it be the return value of the following algorithm:

  1. If the response entity body is null, return an empty ArrayBuffer object and terminate these steps.

  2. Return an ArrayBuffer object representing the response entity body.

The blob response entity body is a Blob representing the response entity body. If the blob response entity body has no value assigned to it let it be the return value of the following algorithm:

  1. If the response entity body is null, return an empty Blob object and terminate these steps.

  2. Return a Blob object representing the response entity body.

The document response entity body is either a document representing the response entity body or null. If it is a document, its origin is the XMLHttpRequest origin. If the document response entity body has no value assigned to it let it be the return value of the following algorithm:

  1. If the response entity body is null, return null and terminate these steps.

  2. If final MIME type is not null, text/html, text/xml, application/xml, or does not end in +xml, return null and terminate these steps.

  3. If responseType is the empty string and final MIME type is text/html, return null and terminate these steps.

    This is restricted to responseType being "document" in order to prevent breaking legacy content.

  4. If final MIME type is text/html let, document be a document that represents the response entity body parsed following the rules set forth in the HTML specification for an HTML parser with scripting disabled. [HTML]

  5. Otherwise, let document be a document that represents the result of parsing the response entity body following the rules set forth in the XML specifications. If that fails (unsupported character encoding, namespace well-formedness error, etc.), return null and terminate these steps. [XML] [XMLNS]

    Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.

  6. Return document.

The JSON response entity body is an ECMAScript value representing the response entity body. The JSON response entity body is the return value of the following algorithm:

  1. Let JSON text be the response entity body decoded using UTF-8. Remove one leading U+FEFF BYTE ORDER MARK character, if present.

  2. Return the result of invoking the parse function of the JSON object defined in ECMAScript, with JSON text as its only argument, or null if that function throws an exception. [ECMASCRIPT]

The text response entity body is a string representing the response entity body. The text response entity body is the return value of the following algorithm:

  1. If the response entity body is null, return the empty string and terminate these steps.

  2. Let charset be the final charset.

  3. Let mime be the final MIME type.

  4. If responseType is the empty string, charset is null, and mime is either null, text/xml, application/xml or ends in +xml, use the rules set forth in the XML specifications to determine the character encoding. Let charset be the determined character encoding. [XML] [XMLNS]

    This is restricted to responseType being the empty string to keep the non-legacy responseType value "text" simple.

  5. If charset is null then, for each of the rows in the following table, starting with the first one and going down, if the first bytes of bytes match the bytes given in the first column, then let charset be the encoding given in the cell in the second column of that row. If there is no match charset remains null.

    Bytes in Hexadecimal Description
    FE FF UTF-16BE BOM
    FF FE UTF-16LE BOM
    EF BB BF UTF-8 BOM
  6. If charset is null let charset be UTF-8.

  7. Return the result of decoding the response entity body using charset. Replace bytes or sequences of bytes that are not valid according to the charset with a single U+FFFD REPLACEMENT CHARACTER character. Remove one leading U+FEFF BYTE ORDER MARK character, if present.

Authors are strongly encouraged to always encode their resources using UTF-8.

4.8.6 The overrideMimeType() method

client . overrideMimeType(mime)

Sets the Content-Type header for the response to mime.

Throws an "InvalidStateError" exception if the state is LOADING or DONE.

Throws a "SyntaxError" exception if mime is not a valid media type.

The overrideMimeType(mime) method must run these steps:

  1. If the state is LOADING or DONE, throw an "InvalidStateError" exception and terminate these steps.

  2. If parsing mime analogously to the value of the Content-Type headers fails, throw a "SyntaxError" exception and terminate these steps.

  3. If a MIME type is successfully parsed set override MIME type to that MIME type, excluding any parameters.

  4. If a charset parameter is successfully parsed set override charset to its value.

4.8.7 The responseType attribute

client . responseType [ = value ]

Returns the response type.

Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text".

When set: throws an "InvalidStateError" exception if the state is LOADING or DONE.

When set: throws an "InvalidAccessError" exception if the synchronous flag is set and there is an associated XMLHttpRequest document.

The responseType attribute must return its value. Initially its value must be the empty string.

Setting the responseType attribute must run these steps:

  1. If the state is LOADING or DONE, throw an "InvalidStateError" exception and terminate these steps.

  2. If there is an associated XMLHttpRequest document and the synchronous flag is set, throw an "InvalidAccessError" exception and terminate these steps.

  3. Set the responseType attribute's value to the given value.

4.8.8 The response attribute

client . response

Returns the response entity body.

The response attribute must return the result of running these steps:

If responseType is the empty string or "text"
  1. If the state is not LOADING or DONE, return the empty string and terminate these steps.

  2. If the error flag is set, return the empty string and terminate these steps.

  3. Return the text response entity body.

Otherwise
  1. If the state is not DONE, return null and terminate these steps.

  2. If the error flag is set, return null and terminate these steps.

  3. If responseType is "arraybuffer"

    Return the arraybuffer response entity body.

    If responseType is "blob"

    Return the blob response entity body.

    If responseType is "document"

    Return the document response entity body.

    If responseType is "json"

    Return the JSON response entity body.

4.8.9 The responseText attribute

client . responseText

Returns the text response entity body.

Throws an "InvalidStateError" exception if responseType is not the empty string or "text".

The responseText attribute must return the result of running these steps:

  1. If responseType is not the empty string or "text", throw an "InvalidStateError" exception and terminate these steps.

  2. If the state is not LOADING or DONE, return the empty string and terminate these steps.

  3. If the error flag is set, return the empty string and terminate these steps.

  4. Return the text response entity body.

4.8.10 The responseXML attribute

client . responseXML

Returns the document response entity body.

Throws an "InvalidStateError" exception if responseType is not the empty string or "document".

The responseXML attribute must return the result of running these steps:

  1. If responseType is not the empty string or "document", throw an "InvalidStateError" exception and terminate these steps.

  2. If the state is not DONE, return null and terminate these steps.

  3. If the error flag is set, return null and terminate these steps.

  4. Return the document response entity body.

The responseXML attribute has XML in its name for historical reasons. It also returns HTML resources as documents.

4.9 Events summary

This section is non-normative.

The following events are dispatched on XMLHttpRequest and/or XMLHttpRequestUpload objects:

Event name Interface Dispatched when…
readystatechange Event The readyState attribute changes at some seemingly arbitrary times for historical reasons.
loadstart ProgressEvent When the request starts.
progress ProgressEvent While sending and loading data.
abort ProgressEvent When the request has been aborted. For instance, by invoking the abort() method.
error ProgressEvent When the request has failed.
load ProgressEvent When the request has successfully completed.
timeout ProgressEvent When the author specified timeout has passed before the request could complete.
loadend ProgressEvent When the request has completed (either in success or failure).

5 Interface FormData

The FormData object represents an ordered collection of entries. Each entry has a name, a value, a type, and optionally a filename (if type is "file").

[Constructor,
 Constructor(HTMLFormElement form)]
interface FormData {
  void append(DOMString name, Blob value, optional DOMString filename);
  void append(DOMString name, DOMString value);
};

5.1 Constructors

fd = new FormData()

Returns a new FormData object.

The FormData() constructor must return a new FormData object.

The FormData(form) constructor must return a new FormData object with as entries the result of constructing the form data set for form.

5.2 The append() method

fd . append(name, value [, filename])

Appends a new name/value-pair to the FormData object, optionally with a filename.

The append(name, value, filename) method must create a new entry with the following parameters set and append it to the end of the collection the FormData object represents:

  • Set its name to name.
  • Set its value to value.
  • Set its type to "text" if value is a string and "file" if it is a Blob.
  • If its type is "file" set its filename to "blob".
  • If its type is "file" and value is a File whose name attribute is not the empty string, set entry's filename to the attribute's value.
  • If the filename parameter is not omitted set entry's filename to filename.

References

Normative references

[COOKIES]
HTTP State Management Mechanism, Adam Barth. IETF.
[CORS]
Cross-Origin Resource Sharing, Anne van Kesteren. W3C.
[DOM]
DOM4, Anne van Kesteren, Aryeh Gregor and Ms2ger. W3C.
[ECMASCRIPT]
ECMAScript Language Specification. ECMA.
[FILEAPI]
File API, Arun Ranganathan and Jonas Sicking. W3C.
[HTML]
HTML, Ian Hickson. WHATWG.
[HTTP]
Hypertext Transfer Protocol -- HTTP/1.1, Roy Fielding, James Gettys, Jeffrey Mogul et al.. IETF.
[HTTPAUTH]
HTTP Authentication: Basic and Digest Access Authentication, J. Franks, Phillip Hallam-Baker, J. Hostetler et al.. IETF.
[HTTPVERBSEC]
Multiple vendors' web servers enable HTTP TRACE method by default. US-CERT.
Microsoft Internet Information Server (IIS) vulnerable to cross-site scripting via HTTP TRACK method. US-CERT.
HTTP proxy default configurations allow arbitrary TCP connections. US-CERT.
[PROGRESSEVENTS]
Progress Events, Anne van Kesteren. W3C.
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels, Scott Bradner. IETF.
[TYPEDARRAY]
Typed Array, David Herman and Kenneth Russell. Khronos.
[WEBIDL]
Web IDL, Cameron McCormack. W3C.
[XML]
Extensible Markup Language, Tim Bray, Jean Paoli, C. M. Sperberg-McQueen et al.. W3C.
[XMLNS]
Namespaces in XML, Tim Bray, Dave Hollander, Andrew Layman et al.. W3C.

Acknowledgments

The editor would like to thank Addison Phillips, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Chris Marrin, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Andersson, David Flanagan, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Doug Schepers, Douglas Livingstone, Elliotte Harold, Eric Lawrence, Eric Uhrhane, Erik Dahlström, Geoffrey Sneddon, Gideon Cohn, Gorm Haug Eriksen, Håkon Wium Lie, Hallvord R. M. Steen, Henri Sivonen, Huub Schaeks, Ian Davis, Ian Hickson, Ivan Herman, Jarred Nicholls, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, 呂康豪 (Kang-Hao Lu), Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mohamed Zergaoui, Ms2ger, Odin Hørthe Omdal, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Taylor, Robin Berjon, Rune Halvorsen, Ruud Steltenpool, Sergiu Dumitriu, Sigbjørn Finne, Simon Pieters, Stewart Brodie, Sunava Dutta, Thomas Roessler, Tom Magliery, Yehuda Katz, and Zhenbin Xu for their contributions to this specification.

Special thanks to the Microsoft employees who first implemented the XMLHttpRequest interface, which was first widely deployed by the Windows Internet Explorer browser.

Special thanks also to the WHATWG for drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to HTML). [HTML]

Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)

'Language > JAVASCRIPT' 카테고리의 다른 글

마우스 커서 포지션 이동  (0) 2013.05.22
XMLHttpRequest 고급 기능  (1) 2013.04.29
XMLHttpRequest  (0) 2013.04.29
자바스크립트  (0) 2013.02.22
팝업창에 POST로 값넘기기  (0) 2012.11.22
:

XMLHttpRequest

Language/JAVASCRIPT 2013. 4. 29. 18:07

http://www.w3.org/TR/2012/NOTE-XMLHttpRequest1-20120117/#event-handler-attributes



Abstract

The XMLHttpRequest specification defines an API that provides scripted client functionality for transferring data between a client and a server.

Status of this Document

Beware. This specification was last published as a Candidate Recommendation, but it is no longer in active maintenance, contains known errors, and the Web Applications Working Group does not intend to maintain it further. See XMLHttpRequest for the Working Group's latest specification.

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This is the 17 January 2012 Working Group Note of XMLHttpRequest. Please send comments to public-webapps@w3.org (archived) with [XHR-NOTE] at the start of the subject line.

Publication as a W3C Working Group Note does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document is produced by the Web Applications (WebApps) Working Group. The WebApps Working Group is part of the Rich Web Clients Activity in the W3C Interaction Domain.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

The XMLHttpRequest object implements an interface exposed by a scripting engine that allows scripts to perform HTTP client functionality, such as submitting form data or loading data from a server. It is the ECMAScript HTTP API.

The name of the object is XMLHttpRequest for compatibility with the Web, though each component of this name is potentially misleading. First, the object supports any text based format, including XML. Second, it can be used to make requests over both HTTP and HTTPS (some implementations support protocols in addition to HTTP and HTTPS, but that functionality is not covered by this specification). Finally, it supports "requests" in a broad sense of the term as it pertains to HTTP; namely all activity involved with HTTP requests or responses for the defined HTTP methods.

Some simple code to do something with data from an XML document fetched over the network:

function test(data) {
 // taking care of data
}

function handler() {
 if(this.readyState == 4 && this.status == 200) {
  // so far so good
  if(this.responseXML != null && this.responseXML.getElementById('test').firstChild.data)
     // success!
   test(this.responseXML.getElementById('test').firstChild.data);
  else
   test(null);
 } else if (this.readyState == 4 && this.status != 200) {
  // fetched the wrong page or network error...
  test(null);
 }
}

var client = new XMLHttpRequest();
client.onreadystatechange = handler;
client.open("GET", "unicorn.xml");
client.send();

If you just want to log a message to the server:

function log(message) {
 var client = new XMLHttpRequest();
 client.open("POST", "/log");
 client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
 client.send(message);
}

Or if you want to check the status of a document on the server:

function fetchStatus(address) {
 var client = new XMLHttpRequest();
 client.onreadystatechange = function() {
  // in case of network errors this might not give reliable results
  if(this.readyState == 4)
   returnStatus(this.status);
 }
 client.open("HEAD", address);
 client.send();
}

2. Conformance Criteria

Everything in this specification is normative except for diagrams, examples, notes and sections marked non-normative.

The key words must, must not, should, should not, and may in this document are to be interpreted as described in RFC 2119. [RFC2119]

This specification defines the following classes of products:

Conforming user agent

A user agent must behave as described in this specification in order to be considered conformant.

If the user agent is not a conforming XML user agent the XML response entity body must (always) be null.

User agents may implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.

Conforming XML user agent

An XML user agent must be a conforming user agent and must be a conforming XML processor that reports violations of namespace well-formedness. [XML]

2.1. Dependencies

This specification relies on several underlying specifications.

DOM

A conforming user agent must support at least the subset of the functionality defined in DOM Events and DOM Core that this specification relies upon, such as various exceptions and EventTarget. [DOM2Events] [DOM3Core]

HTML5

A conforming user agent must support at least the subset of the functionality defined in HTML5 that this specification relies upon, such as the basics of the Window object and serializing a Document object. [HTML5]

The Window Object 1.0 draft is not referenced normatively as it appears to be no longer maintained and HTML5 defines the Window object in more detail. This specification already depends on HTML5 for other reasons so there is not much additional overhead because of this.

HTTP

A conforming user agent must support some version of the HTTP protocol. Requirements regarding HTTP are made throughout the specification. [RFC2616]

Web IDL

A conforming user agent must also be a conforming implementation of the IDL fragments in this specification, as described in the Web IDL specification. [WebIDL]

2.2. Terminology

Convert a DOMString to a sequence of Unicode characters is defined by the Web IDL specification. [WebIDL]

The term user credentials for the purposes of this specification means cookies, HTTP authentication, and client-side SSL certificates. Specifically it does not refer to proxy authentication or the Origin header. [COOKIES]

The terms and algorithms <fragment>, <scheme>, cookie-free Document object, document base URL, document's character encoding, event handler attributes, event handler event type, fetch, fully active, Function, innerHTML, origin, preferred MIME name, resolve a URL, same origin, storage mutex, task, task source, task queues, URL, URL character encoding, queue a task, and valid MIME type are defined by the HTML5 specification. [HTML5]

The term entity body is used as described in RFC 2616. Method token is used as described in section 5.1.1 of RFC 2616. field-name and field-value are used as described in section 4.2 of RFC 2616. [RFC2616]

To deflate a DOMString into a byte sequence means to create a sequence of bytes such that the nth byte of the sequence is equal to the low-order byte of the nth code point in the original DOMString.

To inflate a byte sequence into a DOMString means to create a DOMString such that the nth code point has 0x00 as the high-order byte and the nth byte of the byte sequence as the low-order byte.

userinfo is used as described in section 3.2.1 of RFC 3986. [RFC3986]

To dispatch a readystatechange event means that an event with the name readystatechange, which does not bubble and is not cancelable, and which uses the Event interface, is to be dispatched at the XMLHttpRequest object.

2.3. Extensibility

User agents, Working Groups, and other interested parties are strongly encouraged to discuss extensions on a relevant public forum, preferably public-webapps@w3.org. If this is for some reason not possible prefix the extension in some way and start the prefix with an uppercase letter. E.g. if company Foo wants to add a private method bar() it could be named FooBar() to prevent clashes with a potential future standardized bar().

3. The XMLHttpRequest Interface

The XMLHttpRequest object can be used by scripts to programmatically connect to their originating server via HTTP.

[NoInterfaceObject]
interface XMLHttpRequestEventTarget : EventTarget {
  // for future use
};

[Constructor]
interface XMLHttpRequest : XMLHttpRequestEventTarget {
  // event handler attributes
           attribute Function onreadystatechange;

  // states
  const unsigned short UNSENT = 0;
  const unsigned short OPENED = 1;
  const unsigned short HEADERS_RECEIVED = 2;
  const unsigned short LOADING = 3;
  const unsigned short DONE = 4;
  readonly attribute unsigned short readyState;

  // request
  void open(DOMString method, DOMString url);
  void open(DOMString method, DOMString url, boolean async);
  void open(DOMString method, DOMString url, boolean async, DOMString? user);
  void open(DOMString method, DOMString url, boolean async, DOMString? user, DOMString? password);
  void setRequestHeader(DOMString header, DOMString value);
  void send();
  void send(Document data);
  void send([AllowAny] DOMString? data);
  void abort();

  // response
  readonly attribute unsigned short status;
  readonly attribute DOMString statusText;
  DOMString getResponseHeader(DOMString header);
  DOMString getAllResponseHeaders();
  readonly attribute DOMString responseText;
  readonly attribute Document responseXML;
};

3.1. Origin and Base URL

Each XMLHttpRequest object has an associated XMLHttpRequest origin and an XMLHttpRequest base URL.

This specification defines their values when the global object is represented by the Window object. When the XMLHttpRequest object is used in other contexts their values will have to be defined as appropriate for that context. That is considered to be out of scope for this specification.

In environments where the global object is represented by the Window object the XMLHttpRequest object has an associated XMLHttpRequest Document which is the Document object associated with the Window object for which the XMLHttpRequest interface object was created.

The XMLHttpRequest Document is used to determine the XMLHttpRequest origin and XMLHttpRequest base URL at a later stage.

3.2. Task Sources

The task source used by this specification is the XMLHttpRequest task source.

3.3. Constructors

client = new XMLHttpRequest()
Returns a new XMLHttpRequest object.

When the XMLHttpRequest() constructor is invoked, the user agent must return a new XMLHttpRequest object.

3.4. Event Handler Attributes

The following is the event handler attribute (and its corresponding event handler event type) that must be supported as DOM attribute by the XMLHttpRequest object:

event handler attribute event handler event type
onreadystatechange readystatechange

3.5. States

client . readyState

Returns the current state.

The XMLHttpRequest object can be in several states. The readyState attribute must return the current state, which must be one of the following values:

UNSENT (numeric value 0)

The object has been constructed.

OPENED (numeric value 1)

The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.

HEADERS_RECEIVED (numeric value 2)

All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

LOADING (numeric value 3)

The response entity body is being received.

DONE (numeric value 4)

The data transfer has been completed or something went wrong during the transfer (e.g. infinite redirects).

The OPENED state has an associated send() flag that indicates whether the send() method has been invoked. It can be either true or false and has an initial value of false.

The DONE state has an associated error flag that indicates some type of network error or abortion. It can be either true or false and has an initial value of false.

3.6. Request

The XMLHttpRequest object holds the following request metadata variables:

The asynchronous flag
True when fetching is done asychronously. False when fetching is done synchronously.
The request method
The method used in the request.
The request URL
The URL used in the request.
The request username
The username used in the request or null if there is no username.
The request password
The password used in the request or null if there is no password.
The author request headers
A list consisting of HTTP header name/value pairs to be used in the request.
The request entity body
The entity body used in the request.

3.6.1. The open() method

client . open(method, url, async, user, password)

Sets the request method, request URL, asynchronous flag, request username, and request password.

Throws a SYNTAX_ERR exception if one of the following is true:

  • method is not a valid HTTP method.
  • url cannot be resolved.
  • url contains the "user:password" format in the userinfo production.

Throws a SECURITY_ERR exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.

Throws a SECURITY_ERR exception if the origin of url does not match the XMLHttpRequest origin.

Throws a NOT_SUPPORTED_ERR exception if the <scheme> of url is not supported.

When the open(method, url, async, user, password) method is invoked, the user agent must run these steps (unless otherwise indicated):

  1. If the XMLHttpRequest object has an associated XMLHttpRequest Document run these substeps:

    1. If the XMLHttpRequest Document is not fully active raise an INVALID_STATE_ERR exception and terminate the overall set of steps.

    2. Let XMLHttpRequest base URL be the document base URL of the XMLHttpRequest Document.

    3. Let XMLHttpRequest origin be the origin of the XMLHttpRequest Document.

  2. If any code point in method is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating method it does not match the Method token production raise a SYNTAX_ERR exception and terminate these steps. Otherwise let method be the result of deflating method.

  3. If method is a case-insensitive match for CONNECT, DELETE, GET, HEAD, OPTIONS, POST, PUT, TRACE, or TRACK subtract 0x20 from each byte in the range 0x61 (ASCII a) to 0x7A (ASCII z).

    If it does not match any of the above, it is passed through literally, including in the final request.

  4. If method is a case-sensitive match for CONNECT, TRACE, or TRACK raise a SECURITY_ERR exception and terminate these steps.

    Allowing these methods poses a security risk. [HTTPVERBSEC]

  5. Let url be a URL.

  6. Let URL character encoding of url be UTF-8.

  7. Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error raise a SYNTAX_ERR exception and terminate these steps.

  8. Drop <fragment> from url.

  9. If url contains an unsupported <scheme> raise a NOT_SUPPORTED_ERR and terminate these steps.

  10. If the "user:password" format in the userinfo production is not supported for the relevant scheme and url contains this format raise a SYNTAX_ERR and terminate these steps.

  11. If url contains the "user:password" format let temp user be the user part and temp password be the password part.

  12. If url just contains the "user" format let temp user be the user part.

  13. If the origin of url is not same origin with the XMLHttpRequest origin raise a SECURITY_ERR exception and terminate these steps.

  14. Let async be the value of the async argument or true if it was omitted.

  15. If the user argument was not omitted follow these sub steps:

    1. If user is null let temp user be null.

    2. Otherwise let temp user be user.

    These steps override anything that may have been set by the url argument.

  16. If the password argument was not omitted follow these sub steps:

    1. If password is null let temp password be null.

    2. Otherwise let temp password be password.

    These steps override anything that may have been set by the url argument.

  17. Abort the send() algorithm.

  18. The user agent should cancel any network activity for which the object is responsible.

  19. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove those tasks.

  20. Set variables associated with the object as follows:

  21. Switch the the state to OPENED.

  22. Dispatch a readystatechange event.

3.6.2. The setRequestHeader() method

client . setRequestHeader(header, value)

Appends an header to the list of author request headers or if the header is already in the author request headers its value appended to.

Throws an INVALID_STATE_ERR exception if the state is not OPENED or if the send() flag is true.

Throws a SYNTAX_ERR exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value.

As indicated in the algorithm below certain headers cannot be set and are left up to the user agent. In addition there are certain other headers the user agent will take control of if they are not set by the author as indicated at the end of the send() method section.

When the setRequestHeader(header, value) method is invoked, the user agent must run these steps:

  1. If the state is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the send() flag is true raise an INVALID_STATE_ERR exception and terminate these steps.

  3. If any code point in header is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating header it does not match the field-name production raise a SYNTAX_ERR exception and terminate these steps. Otherwise let header be the result of deflating header.

  4. If any code point in value is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS or after deflating value it does not match the field-value production raise a SYNTAX_ERR exception and terminate these steps. Otherwise let value be the result of deflating value.

    The empty string is legal and represents the empty header value.

  5. Terminate these steps if header is a case-insensitive match for one of the following headers:

    • Accept-Charset
    • Accept-Encoding
    • Connection
    • Content-Length
    • Cookie
    • Cookie2
    • Content-Transfer-Encoding
    • Date
    • Expect
    • Host
    • Keep-Alive
    • Referer
    • TE
    • Trailer
    • Transfer-Encoding
    • Upgrade
    • User-Agent
    • Via

    … or if the start of header is a case-insensitive match for Proxy- or Sec- (including when header is just Proxy- or Sec-).

    The above headers are controlled by the user agent to let it control those aspects of transport. This guarantees data integrity to some extent. Header names starting with Sec- are not allowed to be set to allow new headers to be minted that are guaranteed not to come from XMLHttpRequest.

  6. If header is not in the author request headers list append header with its associated value to the list and terminate these steps.

  7. If header is in the author request headers list either use multiple headers, combine the values or use a combination of those (section 4.2, RFC 2616). [RFC2616]

See also the send() method regarding user agent header handling for caching, authentication, proxies, and cookies.

// The following script:
var client = new XMLHttpRequest();
client.open('GET', 'demo.cgi');
client.setRequestHeader('X-Test', 'one');
client.setRequestHeader('X-Test', 'two');
client.send();

// ...would result in the following header being sent:
...
X-Test: one, two
...

3.6.3. The send() method

client . send(data)

Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD.

Throws an INVALID_STATE_ERR exception if the state is not OPENED or if the send() flag is true.

When the send(data) method is invoked, the user agent must run the following steps (unless otherwise noted). This algorithm gets aborted when the open() or abort() method is invoked. When the send() algorithm is aborted the user agent must terminate the algorithm after finishing the step it is on.

The send() algorithm can only be aborted when the asynchronous flag is true and only after the method call has returned.

  1. If the state is not OPENED raise an INVALID_STATE_ERR exception and terminate these steps.

  2. If the send() flag is true raise an INVALID_STATE_ERR exception and terminate these steps.

  3. If the request method is a case-sensitive match for GET or HEAD act as if data is null.

    If the data argument has been omitted or is null, do not include a request entity body and go to the next step.

    Otherwise, let encoding be null, mime type be null, and then follow these rules:

    If data is a Document

    Let encoding be the preferred MIME name of the character encoding of data. If encoding is UTF-16 change it to UTF-8.

    Let mime type be "application/xml;charset=" followed by encoding.

    Let the request entity body be the result of getting the innerHTML attribute on data converted to Unicode and encoded as encoding. Re-raise any exception this raises.

    In particular, if the document cannot be serialized an INVALID_STATE_ERR exception is raised.

    Subsequent changes to the Document have no effect on what is submitted.

    If data is a DOMString

    Let encoding be UTF-8.

    Let mime type be "text/plain;charset=UTF-8".

    Let the request entity body be data converted to Unicode and encoded as UTF-8.

    If a Content-Type header is set using setRequestHeader() whose value is a valid MIME type and has a charset parameter whose value is not a case-insensitive match for encoding, and encoding is not null, set all the charset parameters of the Content-Type header to encoding.

    If no Content-Type header has been set using setRequestHeader() and mime type is not null set a Content-Type request header with as value mime type.

  4. If the asynchronous flag is false release the storage mutex.

  5. Set the error flag to false.

  6. If the asynchronous flag is true run these substeps:

    1. Set the send() flag to true.

    2. Dispatch a readystatechange event.

      The state does not change. The event is dispatched for historical reasons.

    3. Return the send() method call, but continue running the steps in this algorithm.

  7. Fetch the request URL from origin XMLHttpRequest origin, with the synchronous flag set if the asynchronous flag is false, using HTTP method request method, user request username (if non-null) and password request password (if non-null), taking into account the request entity body, list of author request headers and the rules listed at the end of this section.

    If the asynchronous flag is false

    While making the request also follow the same-origin request event rules.

    The send() method call will now be returned by virtue of this algorithm ending.

    If the asynchronous flag is true

    Make progress notifications.

    Make upload progress notifications.

    While processing the request, as data becomes available and when the user interferes with the request, queue tasks to update the response entity body and follow the same-origin request event rules.


If the user agent allows the end user to configure a proxy it should modify the request appropriately; i.e., connect to the proxy host instead of the origin server, modify the Request-Line and send Proxy-Authorization headers as specified.


If the user agent supports HTTP Authentication and Authorization is not in the list of author request headers, it should consider requests originating from the XMLHttpRequest object to be part of the protection space that includes the accessed URIs and send Authorization headers and handle 401 Unauthorized requests appropriately.

If authentication fails, Authorization is not in the list of author request headers, request username is null, and request password is null, user agents should prompt the end user for their username and password.

If authentication fails, Authorization is not in the list of author request headers, request username is non-null, and request password is non-null, user agents must not prompt the end user for their username and password. [RFC2617]

End users are not prompted if username/password are provided through the open() API so that authors can implement their own user interface.


If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie and Set-Cookie2 response headers, and sent in the Cookie header) as applicable. [COOKIES]


If the user agent implements a HTTP cache it should respect Cache-Control request headers set by the setRequestHeader() (e.g., Cache-Control: no-cache bypasses the cache). It must not send Cache-Control or Pragma request headers automatically unless the end user explicitly requests such behavior (e.g. by reloading the page).

For 304 Not Modified responses that are a result of a user agent generated conditional request the user agent must act as if the server gave a 200 OK response with the appropriate content. The user agent must allow setRequestHeader() to override automatic cache validation by setting request headers (e.g. If-None-Match or If-Modified-Since), in which case 304 Not Modified responses must be passed through. [RFC2616]


If the user agent implements server-driven content-negotiation it should set Accept-Encoding and Accept-Charset headers as appropriate. For Accept and Accept-Language the user agent must follow these constraints:

Responses must have the content-encodings automatically decoded. [RFC2616]


Besides the author request headers user agents should not include additional request headers other than those mentioned above or other than those authors are not allowed to set using setRequestHeader(). This ensures that authors have a reasonably predictable API.

3.6.4. Infrastructure for the send() method

The same-origin request event rules are as follows:

If the response has an HTTP status code of 301, 302, 303, or 307

If the origin of the URL conveyed by the Location header is same origin with the XMLHttpRequest origin and the redirect does not violate infinite loop precautions, transparently follow the redirect while observing the same-origin request event rules.

Otherwise, this is a network error.

HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.

If the end user cancels the request

This is an abort error.

If there is a network error

In case of DNS errors, TLS negotiation failure, or other type of network errors, this is a network error. Do not request any kind of end user interaction.

This does not include HTTP responses that indicate some type of error, such as HTTP status code 410.

Once all HTTP headers have been received and the asynchronous flag is true (and this is not an HTTP redirect)

Switch to the HEADERS_RECEIVED state.

Once the first byte (or more) of the response entity body has been received and the asynchronous flag is true
If there is no response entity body and the asynchronous flag is true

Switch to the LOADING state.

Once the whole response entity body has been received
If there is no response entity body and the asynchronous flag is false or the state is LOADING

Switch to the DONE state.


When something is said to be a network error run the request error steps for exception NETWORK_ERR.

When something is said to be an abort error run the request error steps for exception ABORT_ERR.

When something is said to be a request error for exception exception run these steps:

  1. The user agent should cancel any network activity for which the object is responsible.

  2. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove those tasks.

  3. Set the response entity body to null.

  4. Empty the list of author request headers.

  5. Set the the error flag to true.

  6. Switch the state to DONE.

  7. If the asynchronous flag is false raise an exception exception and terminate the overall set of steps.

  8. Dispatch a readystatechange event.

    At this point it is clear that the asynchronous flag is true.

  9. Terminate the overall algorithm.

A future version of this specification will dispatch an error/abort event here as well. (Depending on the type of error.)


When it is said to switch to the HEADERS_RECEIVED state run these steps:

  1. Switch the state to HEADERS_RECEIVED.

  2. Dispatch a readystatechange event.

When it is said to switch to the LOADING state run these steps:

  1. Switch the state to LOADING.

  2. Dispatch a readystatechange event.

When it is said to switch to the DONE state run these steps:

  1. If the asynchronous flag is false update the response entity body.

  2. Switch the state to DONE.

  3. Dispatch a readystatechange event.

3.6.5. The abort() method

client . abort()
Cancels any network activity.

When the abort() method is invoked, the user agent must run these steps (unless otherwise noted):

  1. Abort the send() algorithm.

  2. The user agent should cancel any network activity for which the object is responsible.

  3. If there are any tasks from the object's XMLHttpRequest task source in one of the task queues, then remove those tasks.

  4. Set the response entity body to null.

  5. Empty the list of author request headers.

  6. Set the error flag to true.

  7. If the state is UNSENT, OPENED with the send() flag being false, or DONE go to the next step.

    Otherwise run these substeps:

    1. Switch the state to DONE.

    2. Set the send() flag to false.

    3. Dispatch a readystatechange event.

    A future version of this specification will dispatch an abort event here.

  8. Switch the state to UNSENT.

    No readystatechange event is dispatched.

3.7. Response

3.7.1. The status attribute

client . status

Returns the HTTP status code.

The status attribute must return the result of running these steps:

  1. If the state is UNSENT or OPENED return 0 and terminate these steps.

  2. If the error flag is true return 0 and terminate these steps.

  3. Return the HTTP status code.

3.7.2. The statusText attribute

client . statusText

Returns the HTTP status text.

The statusText attribute must return the result of running these steps:

  1. If the state is UNSENT or OPENED return the empty string and terminate these steps.

  2. If the error flag is true return the empty string and terminate these steps.

  3. Return the HTTP status text.

3.7.3. The getResponseHeader() method

client . getResponseHeader(header)

Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2.

When the getResponseHeader(header) is invoked, the user agent must run these steps:

  1. If the state is UNSENT or OPENED return null and terminate these steps.

  2. If the error flag is true return null and terminate these steps.

  3. If any code point in header is higher than U+00FF LATIN SMALL LETTER Y WITH DIAERESIS return null and terminate these steps.

  4. Let header be the result of deflating header.

  5. If header is a case-insensitive match for Set-Cookie or Set-Cookie2 return null and terminate these steps.

  6. If header is a case-insensitive match for multiple HTTP response headers, return the inflated values of these headers as a single concatenated string separated from each other by a U+002C COMMA U+0020 SPACE character pair and terminate these steps.

  7. If header is a case-insensitive match for a single HTTP response header, return the inflated value of that header and terminate these steps.

  8. Return null.

For the following script:

var client = new XMLHttpRequest();
client.open("GET", "unicorns-are-teh-awesome.txt", true);
client.send();
client.onreadystatechange = function() {
  if(this.readyState == 2) {
    print(client.getResponseHeader("Content-Type"));
  }
}

The print() function will get to process something like:

text/plain; charset=UTF-8

3.7.4. The getAllResponseHeaders() method

client . getAllResponseHeaders()

Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.

When the getAllResponseHeaders() method is invoked, the user agent must run the following steps:

  1. If the state is UNSENT or OPENED return the empty string and terminate these steps.

  2. If the error flag is true return the empty string and terminate these steps.

  3. Return all the HTTP headers, excluding headers that are a case-insensitive match for Set-Cookie or Set-Cookie2, inflated, as a single string, with each header line separated by a U+000D CR U+000A LF pair, excluding the status line, and with each header name and header value separated by a U+003A COLON U+0020 SPACE pair.

For the following script:

var client = new XMLHttpRequest();
client.open("GET", "narwhals-too.txt", true);
client.send();
client.onreadystatechange = function() {
 if(this.readyState == 2) {
  print(this.getAllResponseHeaders());
 }
}

The print() function will get to process something like:

Date: Sun, 24 Oct 2004 04:58:38 GMT
Server: Apache/1.3.31 (Unix)
Keep-Alive: timeout=15, max=99
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/plain; charset=utf-8

3.7.5. Response Entity Body

The response MIME type is the MIME type the Content-Type header contains without any parameters or null if the header could not be parsed properly or was omitted. The override MIME type is always null. Final MIME type is the override MIME type unless that is null in which case it is the response MIME type.

The response charset is the value of the charset parameter of the Content-Type header or null if there was no charset parameter or if the header could not be parsed properly or was omitted. The override charset is always null. Final charset is the override charset unless that is null in which case it is the response charset.

Override MIME type and override charset are introduced here solely to make editing several levels of XMLHttpRequest simultaneously somewhat easier. Apologies for any confusion they might cause.


The response entity body is the fragment of the entity body of the response received so far (LOADING) or the complete entity body of the response (DONE). If the response does not have an entity body the response entity body is null.

The response entity body is updated as part of the send() algorithm.


The text response entity body is a DOMString representing the response entity body. The text response entity body is the return value of the following algorithm:

  1. If the response entity body is null return the empty string and terminate these steps.

  2. Let charset be the final charset.

  3. Let mime be the final MIME type.

  4. If charset is null and mime is null, text/xml, application/xml or ends in +xml use the rules set forth in the XML specifications to determine the character encoding. Let charset be the determined character encoding.

  5. If charset is null and mime is text/html follow the rules set forth in the HTML specification to determine the character encoding. Let charset be the determined character encoding. [HTML5]

  6. If charset is null then, for each of the rows in the following table, starting with the first one and going down, if the first bytes of bytes match the bytes given in the first column, then let charset be the encoding given in the cell in the second column of that row. If there is no match charset remains null.

    Bytes in Hexadecimal Description
    FE FF UTF-16BE BOM
    FF FE UTF-16LE BOM
    EF BB BF UTF-8 BOM
  7. If charset is null let charset be UTF-8.

  8. Return the result of decoding the response entity body using charset. Replace bytes or sequences of bytes that are not valid accordng to the charset with a single U+FFFD REPLACEMENT CHARACTER character.

Authors are strongly encouraged to encode their resources using UTF-8.


The document response entity body is either a Document representing the response entity body or null. The document response entity body is the return value of the following algorithm:

  1. If the response entity body is null terminate these steps and return null.

  2. If final MIME type is not null, text/xml, application/xml, and does not end in +xml terminate these steps and return null.

  3. Let document be a cookie-free Document object that represents the result of parsing the response entity body into a document tree following the rules from the XML specifications. If this fails (unsupported character encoding, namespace well-formedness error et cetera) terminate these steps return null. [XML]

    Scripts in the resulting document tree will not be executed, resources referenced will not be loaded and no associated XSLT will be applied.

  4. Return document.

3.7.6. The responseText attribute

client . responseText

Returns the text response entity body.

The responseText attribute must return the result of running these steps:

  1. If the state is not LOADING or DONE return the empty string and terminate these steps.

  2. Return the text response entity body.

3.7.7. The responseXML attribute

client . responseXML

Returns the document response entity body.

The responseXML attribute must return the result of running these steps:

  1. If the state is not DONE return null and terminate these steps.

  2. Return the document response entity body.

4. Exceptions

Several algorithms in this specification may result in an exception being thrown. These exceptions are all part of the group ExceptionCode and use the DOMException object, which is defined in DOM Level 3 Core. In addition this specification extends the ExceptionCode group with several new constants as indicated below. [DOM3Core]

Thus, exceptions used by this specification and not defined in this section are defined by DOM Level 3 Core.

const unsigned short SECURITY_ERR = 18;
const unsigned short NETWORK_ERR = 19;
const unsigned short ABORT_ERR = 20;

The SECURITY_ERR exception is raised if an attempt is made to perform an operation or access some data in a way that would be a security risk or a violation of the user agent's security policy.

The NETWORK_ERR exception is raised when a network error occurs in synchronous requests.

The ABORT_ERR exception is raised when the user aborts a request in synchronous requests.

These exceptions will be folded into an update of DOM Level 3 Core in due course, as they are appropriate for other API specifications as well.

References

Unless marked "Non-normative" these references are normative.

[COOKIES]
HTTP State Management Mechanism (work in progress), A. Barth. IETF.
[DOM2Events]
Document Object Model (DOM) Level 2 Events Specification, T. Pixley. W3C.
[DOM3Core]
Document Object Model (DOM) Level 3 Core Specification, A. Le Hors, P. Le Hégaret, L. Wood, G. Nicol, J. Robie, M. Champion, S. Byrne. W3C.
[ECMAScript]
ECMAScript Language Specification. ECMA.
[HTML5]
HTML5 (work in progress), I. Hickson. W3C.
HTML5 (work in progress), I. Hickson. WHATWG.
[HTTPVERBSEC]
(Non-normative) Multiple vendors' web servers enable HTTP TRACE method by default, US-CERT.
(Non-normative) Microsoft Internet Information Server (IIS) vulnerable to cross-site scripting via HTTP TRACK method, US-CERT.
(Non-normative) HTTP proxy default configurations allow arbitrary TCP connections, US-CERT.
[RFC2046]
Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein. IETF.
[RFC2119]
Key words for use in RFCs to Indicate Requirement Levels, S. Bradner. IETF.
[RFC2616]
Hypertext Transfer Protocol -- HTTP/1.1, R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee. IETF.
[RFC2617]
HTTP Authentication: Basic and Digest Access Authentication, P. Hallam-Baker, J. Hostetler, S. Lawrence, P. Leach, A. Luotonen, L. Stewart. IETF.
[RFC3986]
Uniform Resource Identifier (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter. IETF.
[RFC3987]
Internationalized Resource Identifiers (IRIs), M. Duerst, M. Suignard. IETF.
[WebIDL]
Web IDL (work in progress), C. McCormack. W3C.
[XML]
Extensible Markup Language (XML) 1.0, T. Bray, J. Paoli, C. Sperberg-McQueen, E. Maler, F. Yergeau. W3C.
Namespaces in XML, T. Bray, D. Hollander, A. Layman, R. Tobin, H. S. Thompson. W3C.

Acknowledgments

The editor would like to thank Addison Phillips, Ahmed Kamel, Alex Hopmann, Alex Vincent, Alexey Proskuryakov, Asbjørn Ulsberg, Boris Zbarsky, Björn Höhrmann, Cameron McCormack, Christophe Jolif, Charles McCathieNevile, Dan Winship, David Andersson, David Håsäther, David Levin, Dean Jackson, Denis Sureau, Doug Schepers, Douglas Livingstone, Elliotte Harold, Eric Lawrence, Erik Dahlström, Geoffrey Sneddon, Gideon Cohn, Gorm Haug Eriksen, Håkon Wium Lie, Hallvord R. M. Steen, Huub Schaeks, Ian Davis, Ian Hickson, Ivan Herman, Jeff Walden, Jens Lindström, Jim Deegan, Jim Ley, Joe Farro, Jonas Sicking, Julian Reschke, Karl Dubost, Lachlan Hunt, Maciej Stachowiak, Magnus Kristiansen, Marc Hadley, Marcos Caceres, Mark Baker, Mark Birbeck, Mark Nottingham, Mark S. Miller, Martin Hassman, Mohamed Zergaoui, Olli Pettay, Pawel Glowacki, Peter Michaux, Philip Taylor, Robin Berjon, Rune Halvorsen, Ruud Steltenpool, Simon Pieters, Stewart Brodie, Sunava Dutta, Thomas Roessler, Tom Magliery, and Zhenbin Xu for their contributions to this specification.

Special thanks to the Microsoft employees who first implemented the XMLHttpRequest interface, which was first widely deployed by the Windows Internet Explorer browser.

Special thanks also to the WHATWG for drafting an initial version of this specification in their Web Applications 1.0 document (now renamed to HTML5). [HTML5]

Thanks also to all those who have helped to improve this specification by sending suggestions and corrections. (Please, keep bugging us with your issues!)

'Language > JAVASCRIPT' 카테고리의 다른 글

XMLHttpRequest 고급 기능  (1) 2013.04.29
XMLHttpRequest Level 2  (0) 2013.04.29
자바스크립트  (0) 2013.02.22
팝업창에 POST로 값넘기기  (0) 2012.11.22
자바스크립트 정규식  (0) 2012.01.04
:

인코딩 - 8859_1의 비밀(?)

Language/JSP 2013. 4. 23. 18:12

Open source로 구해지는 java source code를 들여다 보면 

하고 많은 문자셋들 중에 유독 '8859_1'을 많이 보게 된다.

'아니 저런 특정 문자셋을, 그것도 8비트밖에 지원하지 않는 문자셋을 코드에다 박아 버리면 
 쓰는 사람들은 어쩌란 거지?'

이런 생각이 들 때가 있을 것이다.
한때 나도 그랬었고..

그러나 정말 잘못 쓴 경우도 있겠지만, 많은 경우 '8859_1'의 사용은 나름 합리성을 띄고 있다.
이를 이해하려면 '8859_1'이 다른 문자셋들과 어떻게 다른가를 알아야 한다.

이전 글에서 언급했 듯이, '8859_1'은 1바이트에 해당하는 256개의 코드에 대해, 즉 0x00 ~ 0xff 까지의 모든 코드에 대해 대응되는 문자를 갖고 있다.

반면 8859_1보다 많은 문자를 거느리고 있는 'EUC-KR', 
이것의 확장형인 'MS949' 나 심지어 모든 글자를 다 포함한다고 여겨도 될 만한 'UTF-8' 조차
가진 문자는 확실히 많지만 모든 바이트 열에 대해 대응되는 문자를 갖고 있는 것은 아니다.

이를 확인하기 위해 다음을 실행해 보자.

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 256; i++) {
            for (int j = 0; j < 256; j++) {
                byte[] bytes = new byte[] {(byte) i, (byte)j };
                String str = new String(bytes, "MS949");
                if (str.charAt(0) == 0xfffd) {
                    System.out.println("for byte sequence{0x" + hex(i) + ", 0x" + hex(j)
                            + "} no character exists... getBytes()[0]=" + str.getBytes("MS949")[0]);
                } else if (str.length() > 1) {
                    // 첫 바이트를 하나의 글자로 인식. i만 취하고 j 루프는 중지.
                    System.out.println("For character{" + hex(i) + "} char = "
                            + str.charAt(0));
                    break;
                } else {
                    System.out.println("for character{" + hex(i) + ", " + hex(j)
                            + "} char = " + str);
                }

            }
        }
    }
    
    /*
     * byte 출력용.
     */
    public static String hex(int i ){
        String hex = Integer.toHexString(i); 
        return (hex.length() > 2) ? hex.substring(hex.length() - 2) : hex;
    }
주루룩 많은 행을 출력하지만 보면 대응되지 않는 글자가 존재함을 알 수 있다.

대략 그림으로 나타내면 다음과 같다.

인식하는 바이트 값이 0x~0x7f 일 경우에는 8859_x 에서 사용되는 글자를 그대로 쓰며 이 때는 한 바이트가 하나의 글자와 매핑된다.
바이트 값이 0x81 이상일 경우에는 그 다음 바이트가 필요하며, 두 바이트를 가지고 하나의 글자를 구성한다. 그리고 이 때 '없는 글자'가 생긴다.
당장 {0x81, 0x00} ~ {0x81, 0x40} 에 해당하는 값에 대해 대응되는 글자가 없다.
없는 글자는 java char로 0xfffd (아마도 UTF-16BE로 {0xff 0xfd} 에 매핑되는 글자) 로 저장되었다가, 다시 MS949로 인코드하면 0x63 글자로 매핑된다. 이 글자가 물음표 '?' 이다
 
모르는 글자를 인코드 할 때 0x63 코드를 매핑하는 것은 Sun JDK에서의 대응 방식이다.
모르는 글자에 대한 대응에는 표준이 없는지 다른 vendor - 이를테면 IBM - 의 JDK에서는 좀 다르게 구현하는 것 같다.
(한편 바이트 값이 0x80이나 0xff 같을 때 이를 디코드하면 그 한 바이트가 '모르는 글자 0xfffd'로 매핑된다. 일반화할 수 있는 규칙은 아닌 것 같다..)
 
다음과 같이 인코드 - 디코드를 많이 거치게 되면 인코드 할 때도, 디코드 할 때도 매핑이 불가한 경우를 만나게 되어 글자들이 깨진다. 이 때의 깨진 글자들은 복구가 절대 안 된다.
그래서 저런 식으로 부주의하게 인코드-디코드를 해 버리면 원래 호환되는 0x00~0x7f 이외의 한글 같은 글자들은 여지없이 깨져 버리고.. 되돌릴 수도 없게 된다.
 
그러나 8859_x 는 모든 바이트 코드에 대한 글자들을 구비하고 있으므로, 이해가 안 되는 이상한 글자로 매핑할 망정 코드를 보존하면서 디코드가 가능하다.
그래서 디코드만 하고, 이를 다시 인코드 할 경우에는 글자 깨짐이 발생하지 않는다.
 
8859_1 뿐만 아니라 8859_2 도 "보관"할 때 가지는 문자가 틀리지만 역시 깨짐 없이 바이트를 보존할 수 있다.
 
물론 그렇게 "보관"한 문자나 인코드가 원활히 되지, 아무 문자열이나 인코드를 하려 한다면
'자기 문자셋에 존재하지 않는 문자를 인코드'하는 경우가 발생해 글자가 깨질 것이다.
이를테면 아래와 같은 경우 당연히 문자셋에 없는 글자를 인코드하려 하므로 글자가 깨진다.
이렇게 되면 '원래 문자열이 2글자였다' 정도 외엔 아무 정보도 남지 않게 된다. (JDK vendor에 따라서는 이마저도 알 수 없게 될 것이다)
 
-----------------------------
 
실제 네트워크를 오가는 데이터는 바이트열의 형태이지만
이를 프로그래밍 언어에서 다룰 때는 문자열로 간주하고 작업할 때가 많다.
그게 편하기 때문이기도 하고,
문자열로서 의미를 가지는 경우가 많기 때문이기도 할 것이다.
 
가장 많이 쓰이는 경우가 웹 어플리케이션에서의 파일 다운로드, 아마도 그 다음이 소켓통신 (헤더를 읽어들이거나 생성할 때) 같은 경우일 것이다.
<< 다운로드 시 설정>>

response.addHeader("Content-disposition", "attachment;filename=" + ... + "" );

이 때 인코딩/디코딩 작업이 필요한데, 디코드 시 바이트들을 깨뜨리지 않고 문자열로 얻고 싶다면 '8859_x'을 쓰는 것이 현명한 방책이라 하겠다.

물론 그 중에서도 많은 서버들이 위의 filename 을 ISO-Latin1(혹은 Latin1, 8859_1) 로 인코딩 해 보내기 때문에 같은 Latin 계열이라도 '8859_1' 즉 'Latin1'을 택하는 것이 좋다.
이는 표준이라고 하는데 문서 확인은 안 해 봤다. (어디 있는지 찾기 정말 힘들던데..)
 
출처 - http://blog.naver.com/anabaral?Redirect=Log&logNo=130043451093


'Language > JSP' 카테고리의 다른 글

JAX-RS TUTORIALS  (0) 2013.07.10
Configuring JAX-RS services in container with Spring configuration file.  (0) 2013.07.10
Tomcat과 한글 인코딩  (0) 2013.04.23
JSP pageEncoding속성, 케릭터셋(charset)  (0) 2013.02.13
mybatis[SqlSession]  (0) 2012.11.07
:

Tomcat과 한글 인코딩

Language/JSP 2013. 4. 23. 18:10

개요

웹프로그래밍을 하다보면 항상 한글인코딩과 관련된 문제에 봉착하게 된다. 그럴때면 보통 웹검색을 통해 대부분의 해결책을 찾고는 하였다. 하지만, 그 해결책이라는 것이 대부분 경험담에 불과하고, 우리가 맞닥뜨린 문제와는 미묘하게 다른부분이 있기도 하여 근본적인 해결방법이 되지 않을 경우도 있다. 우연찮게 해결을 하더라도, 시간에 쫒기다보니, 근본적인 원인을 해결하지 못하고 해결하기에 급급하여 다음에 또 비슷한문제를 겪는 악순환을 겪기도 한다.


실제로 톰캣에서 한글이 어떻게 인코딩/디코딩되는걸까?

본인 역시 늘 고민해오던 문제였는데, 마침 시간이 나게되어, JSP파일에서부터 클라이언트의 응답메시지와 요청메시지, 그리고 톰캣에서의 인코딩과정에 대해 간략하게 정리해보았다.


이 글은 톰캣 5.5.x, 와 6.0.x 에서 테스트 되었다.

JSP 인코딩과 HTML 인코딩

우리가 작성한 JSP 파일은 컨테이너(여기서는 톰캣)에 의해 JAVA 파일로 변경이 된다.
이때 첫번째 인코딩이 일어나게 되는데, 이 시점에서 확인하여야할것은 JSP 파일 인코딩과 JSP 문자 인코딩이다. JSP 파일 인코딩과 JSP 문자 인코딩이 다를 경우 여지없이 한글이 깨져 버린다.


JSP 파일 인코딩은 실제 해당 파일이 작성될때 사용된 캐릭터셋으로

Eclipse 같은 툴을 사용하면 확인할 수 있다.


JSP 문자 인코딩은 컨테이너가 JSP파일을 JAVA로 변경하기위해 읽어들일때, 해당 JSP파일이 어떤 문자셋으로 이루어져 있는가를 컨테이너에게 알려주기 위해 JSP의 page 지시자에 선언되어 있는 캐릭터셋이다.

JSP 파일의 문자 인코딩 캐릭터셋은 JSP의 page 지시자의 속성중에 pageEncoding를 확인하면 된다. 디폴트 값은 ISO-8859-1 이지만, ContentType에서 인코딩을 정의 하지 않았을 경우에만 디폴트 값이 적용된다.


예를 들어 다음과 같은 내용의 JSP파일을 생성하였다고 가정하자. (파일 인코딩은 UTF-8이라고 가정한다)


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>테스트</title>
</head>
<body>
<div>
    <form action="/test2.jsp" method="post">
        <input type="text" name="keyword" > <input type="submit">
    </form>

</div>
</body>
</html>


다음은 위의 JSP 파일이 변경된 JAVA 파일의 일부이다.

(서블릿을 컨테이너에 배포한다음 TOMCAT_HOME/work/ 하위에서 찾을 수 있다)


out.write("\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>�����/title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");
      out.write("<div> \r\n");
      out.write("\t<form action=\"/test2.jsp\" method=\"post\">\r\n");
      out.write("\t\t<input type=\"hidden\" name=\"actions\" value=\"test2\" >\r\n


JSP의 <title>의 한글이 깨져 있음을 확인할 수 있다.


page 지시자에는 pageEncoding 뿐만 아니라 contentType 이라는 속성도 있는데, 이 속성은 MIME 타입과 해당 페이지에서 사용될 인코딩 문자셋을 설정한 다. 즉, 이 값에 따라 브라우져가 서버의 메시지를 어떤 문자셋으로 해석할지가 결정되며, 페이지에서 사용되는 문자들의 인코딩 문자셋이 결정된다. 대부분의 브라우져의 기능을 살펴보면 문자 인코딩을 변경하는 메뉴가 있는데, 여기에 기본으로 선택된 값이 contentType에 설정된 값이다.


contentType 이 생략될 경우 pageEncoding 값을 따르며, pageEncoding 까지 생략되면 기본적으로 ISO-8859-1 문자셋을 따른다.


예를 들어 contentType의 값이 UTF-8 이라면 클라이언트의 브라우져는 서버의 응답을 UTF-8로 해석하여 HTML 파일을 화면에 뿌리게 된다. 그리고 페이지의 모든 문자들은 UTF-8의 문자셋을 기반으로 하게된다.


HTML의 meta 태그내의 content 속성은 단순히 메타 태그로써 페이지의 정보를 알려주는 기능외에 실제 인코딩에 관여하지 않는다는 것에 주의하도록 한다.

 <head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>test</title>
</head>


서블릿과 톰캣 인코딩

톰 캣은 클라이언트에서 서버로의 요청메시지를 서블릿 스펙에 따라 기본적으로 ISO-8859-1 로 인코딩되어 처리되도록 되어 있다. 즉, 클라이언트에서의 문자열이(contentType) UTF-8 이든, EUC-KR 이든 ISO-8859-1로 인코딩 된다는 것이다.

(메시지의 인코딩은 앞에서 언급한바대로 웹페이지의 ContetType 값에 따른다)


즉, 다음의 코드가 실행되는 것과 같다.

//UTF-8 인코딩된 메시지
new String( "UTF-8".getByte("UTF-8"),"ISO-8859-1");

//EUC-KR 인코딩된 메시지
new String("EUC-KR".getByte("EUC-KR"),"ISO-8859-1");


어 라? 이상하지 않은가? 한글 처리를 위한 UTF-8이나 EUC-KR은 2바이트 문자인데, 1바이트 문자인 ISO-8859-1로 인코딩하면 문자열이 깨지지 않겠는가? 깨어지는 것처럼 보이지만 실제로는 문자열의 바이트값이 보존된다. 여기서 인코딩/디코딩의 개념과 ISO-8859-1 이라는 문자셋에 대한 이해가 필요하다.


우선 문자셋이라는 것은 글자와 바이트의 매핑관계를 정의하는 것으로 문자셋에 따라 이 매핑관계가 달라진다.

예를 들어 EUC-KR문자셋에서 "테스트" 라는 문자열은 "c5d7bdbac6ae" 바이트배열값으로 매핑된다.

이때 EUC-KR 문자셋은 2바이트 문자셋이므로 c57b값이 "테" 라는 문자열값에 매핑되며 7bdb와 c6ae는 각각 "스"와 "트"에 매핑이된다.

이렇게 문자열을 바이트 시퀀스로 변환하는 과정을 인코딩, 그 반대 과정을 디코딩이라고 한다.


이 론적으로 EUC-KR은 2바이트 문자로써 65535개의 문자를 매핑하는것이 가능하지만 실제로는 대부분의 바이트가 비어있다. 이는 UTF-8이나 KSC5601, MS949 등 마찬가지이다. 문자셋들은 동일한 바이트값에 대한 매핑문자가 서로 다르며, 문자 구성또한 달라 매핑이 불가능한 문자도 있다. 예를 들어 유니코드 "뷁" 문자를 EUC-KR 로 인코딩할경우 "뷁" 문자가 EUC-KR 문자셋에 정의되어 있지 않으므로, 자바는 이를 "?(0X3F)"로 변경해버린다. (이 또한 JVM 벤더에 따라 다르게 동작한다.) "?"로 매칭된 문자는 원래의 유니코드로 디코딩된다고 해도 원래의 "뷁" 문자를 표현하지 못하게된다. 이처럼 문자간의 인코딩/디코딩시에 데이터 손실이 일어나게되는데, ISO-8859-1 문자셋은 1바이트로 이루어져있지만, 유일하게 빈공간없이 모든 바이트값에 대해 문자를 매핑하고 있다. 따라서, ISO-8859-1 문자셋으로 인코딩되었다하더라도 원래 문자셋으로 디코딩만 하면 데이터의 손실없이 원래의 문자를 표현할수 있게된다.

ISO-8859-1 문자셋에 대해서는 다음을 참고하라 (http://en.wikipedia.org/wiki/ISO/IEC_8859-1#ISO-8859-1)


다시 톰캣이야기로 돌아가서 위에서 언급하길 서블릿 스펙에 따라 톰캣은 모든 요청메시지를 ISO-8859-1로 인코딩한다고 하였다.

즉, EUC-KR 문자열의 바이트 값인 "c5d7bdbac6ae"를 톰캣이 받게되면 이 바이트 배열을 ISO-8859-1 문자셋으로 인코딩된것으로 간주하고 ISO-8859-1문자셋을 이용해 디코딩해버린다. 그렇게 되면 "c5d7bdbac6ae" 바이트배열은"Å×½ºÆ®" 이라는 문자열로 디코딩되는데, ISO-8859-1문자셋은 각 바이트에 매칭되는 문자값이 모두 존재하기때문에 의미없는 문자로 표현될지언정 매칭문자가 없어 "?"로 표현될 일이 없다. 즉, 문자열이 깨지지 않는다. 따라서, "Å×½ºÆ®" 문자열을 다시 EUC-KR 문자셋으로 인코딩하게되면 원래의 문자열로 돌아가게되는것이 보장된다.

byte[] bytes = "테스트".getBytes("EUC-KR");
String str = new String(bytes,"ISO-8859-1");
System.out.println(hex(bytes)); //hex() 는 바이트 배열값을 HEX코드로 출력하는 기능
System.out.println(str);
bytes = "Å×½ºÆ®".getBytes("ISO-8859-1");
str = new String(bytes,"EUC-KR");
System.out.println(hex(bytes));
System.out.println(str);
=============================================
c5d7bdbac6ae
Å×½ºÆ®
c5d7bdbac6ae
테스트


톰캣으로 전달된 ISO-8859-1 인코딩된 데이터는 톰캣 내부에서 사용자의 요청메시지를 처리하기위해 request 객체를 생성하는 과정에서 인코딩 과정을 거치게된다. 이때 적용되는 인코딩 문자셋은 기본적으로 null로써 시스템 프로퍼티인 file.encoding에 정의된 인코딩 문자셋(이하, 시스템 인코딩 문자셋)을 사용하도록 되어 있다. 클라이언트의 요청메시지의 원래 인코딩 문자셋과 시스템 인코딩 문자셋이 다르다면 원래의 문자셋으로 복원이 불가능해지므로 한글 인코딩이 깨어지게 된다. 따라서 한글 데이터를 보존하기 위해서는 new String("문자열".getByte("ISO-8859-1"), "EUC-KR") 같이 클라이언트에서 전송시에 사용된 문자셋으로 디코딩 과정을 먼저 실행한다음 원래대로 문자열을 복원하여야 한다. 번거로운 인코딩작업 대신에 클라이언트의 요청 메시지 전체에 대해 명시적으로 인코딩 문자셋을 지정해주는 방법이 있는데, 그 방법은 아래와 같다. (단 인코딩 문자셋은 request 객체가 생성되기전에 정의되어야 한다)

request.setCharacterEncoding("문자셋이름")

톰 캣은 클라이언트의 요청메시지에 대한 request 객체의 생성이 끝나면, 응답 메시지를 작성하기위해 response 객체를 생성하게 된다. 이때 response 객체의 생성시에 사용되는 인코딩 문자셋은 JSP 파일의 page 지시자의 contentType 속성에 정의된 인코딩 문자셋을 따르게 된다. 서버의 응답 메시지를 생성할때 사용되는 인코딩 문자셋과 브라우져에서 이를 해석하는 문자셋이 항상 contentType을 따르도록 되어있으므로 프로그래머는 이 단계에서는 인코딩에 대해 신경쓰지 않아도 된다. 하지만 문제는 request 객체와 response 객체 사이에서 일어난다. 대부분의 응답메시지는 요청메시지의 데이터를 포함하게 되는데, 요청메시지에 대해 디코딩을 완벽하게 수행했다하더라도, request 객체와 response 객체의 인코딩 문자셋이 다르다면 request 객체의 데이터가 response 객체에서 인코딩이 깨어지게 된다.


이렇게 생성된 서버의 응답메시지는 ISO-8850-1 인코딩되어 클라이언트의 브라우져에 전달된다. 전달된 응답 메시지는 클라이언트의 브라우져에서 contentType에 정의된 인코딩 문자셋을 이용하여 해석된 다음 출력되게 된다.


GET과 POST

앞 절에서 클라이언트 요청메시지에 전체에 대해 명시적으로 인코딩 문자셋을 지정하는 방법을 소개하였다. 하지만 이 경우 request 객체가 생성되기 이전에 인코딩 문자셋을 지정하여야 하므로 톰캣에서는 필터를 사용하여 인코딩 문자셋을 지정할 것을 권장하고 있다. 하지만 이 경우에도 약간의 문제가 있다. 클라이언트의 요청메시지는 GET과 POST 두 가지 방식으로 서버에 전달되는데, 필터에 의한 인코딩 문자셋을 지정하는 방법은 POST요청에 한해서만 유효하다는 점이다. GET 방식으로 전달 되는 파라메터는 URL에 포함되어 전달되는데, URL은 요청 메시지 내부의 파라메터는 지정된 인코딩 문자셋을 사용하지않고 기본적으로 ISO-8859-1 인코딩 문자셋에 따라 해석을 하기 때문이다. 따라서 URL에 대한 인코딩 문자셋을 명시적으로 지정해줄 필요가 있다. 이를 위해서는 톰캣의 tomcat_home/conf/server.xml 파일의 Connector 부분의 설정을 변경하여야 한다. 

 ...
    <Connector ... port="8080" URIEncoding="UTF-8" />
...


정리

지금 까지의 이야기를 정리하자면 한글을 적절하게 처리하기 위해서는 우선, 요청 페이지의 contentType을 확인해야 하며, 사용자의 요청메시지가 GET인지, POST인지를 확인한다. 그런다음 각각의 요청메시지 타입에 따라 서버에서 메시지를 처리하는 인코딩 문자셋을 확인한 다음, 마지막으로 응답 페이지의 contentType을 확인하여 이 4가지 인코딩 문자셋이 일치하는가를 살펴보아야 한다.


이 상의 내용은 실제 톰캣을 소스레벨까지 내려가서 살펴본것이아니라, 다분히 개인적인 지식과 경험에 의해 쓰여진 것이므로 다소 사실과는 다를지도 모른다. 하지만, 여러가지 실험과 근거에 의해 작성되었으므로 신뢰할 만하다고 생각한다. 한글 처리로 곤란함을 격게된다면 위의 과정을 밟아가면서 어디에서 인코딩이 깨지는가를 확인해보면 빠르게 문제를 해결을 할 수 있으리라 생각한다. 부디 한글로 인해 고민하는 날이 없기를 바란다.

출처 - http://blog.naver.com/codechaser?Redirect=Log&logNo=80085455490


:

자바스크립트

Language/JAVASCRIPT 2013. 2. 22. 17:48

http://www.java2s.com/Tutorial/JavaScript/CatalogJavaScript.htm


1.Language Basics
1.1.Comments( 3 ) 1.6.Semicolon( 2 ) 
1.2.Expressions( 2 ) 1.7.Source File( 8 ) 
1.3.Keywords( 2 ) 1.8.Variable Scope( 1 ) 
1.4.SCRIPT Tag( 2 ) 1.9.Variables( 12 ) 
1.5.self( 1 ) 
2.Operators
2.1.Arithmetic operator( 15 ) 2.8.Conditional Operator( 4 ) 
2.2.Postfix operator( 4 ) 2.9.Relational Operators( 11 ) 
2.3.Prefix operator( 4 ) 2.10.new( 1 ) 
2.4.Assignment( 7 ) 2.11.delete( 1 ) 
2.5.Bitwise Operator( 19 ) 2.12.Mod( 3 ) 
2.6.Boolean Operators( 5 ) 2.13.typeof( 5 ) 
2.7.Comma Operator( 1 ) 2.14.Operator Precedence( 2 ) 
3.Statement
3.1.var( 1 ) 3.9.Break( 3 ) 
3.2.If( 7 ) 3.10.Label( 1 ) 
3.3.For In( 2 ) 3.11.With( 2 ) 
3.4.For Loop( 9 ) 3.12.void( 1 ) 
3.5.Switch( 7 ) 3.13.try catch( 3 ) 
3.6.while( 7 ) 3.14.throw( 2 ) 
3.7.Do While( 5 ) 3.15.Timing( 1 ) 
3.8.continue( 4 ) 3.16.Dynamic expressions( 1 ) 
4.Development
4.1.assert( 2 ) 4.7.Exception( 8 ) 
4.2.Browser Detect( 1 ) 4.8.instanceof( 1 ) 
4.3.Color( 1 ) 4.9.postError( 1 ) 
4.4.Cookie( 7 ) 4.10.Predefined Exceptions( 1 ) 
4.5.debug( 2 ) 4.11.this( 1 ) 
4.6.Error( 4 ) 4.12.Try Catch( 1 ) 
5.Number Data Type
5.1.Introduction( 15 ) 5.13.MIN_VALUE( 1 ) 
5.2.Boolean( 6 ) 5.14.NaN( 1 ) 
5.3.Integer( 8 ) 5.15.NEGATIVE_INFINITY( 1 ) 
5.4.Float( 4 ) 5.16.null( 1 ) 
5.5.Precision( 1 ) 5.17.POSITIVE_INFINITY( 1 ) 
5.6.Number Constructors( 3 ) 5.18.prototype( 1 ) 
5.7.Number Format( 1 ) 5.19.toExponential( 1 ) 
5.8.Type Conversion( 16 ) 5.20.toLocaleString( 1 ) 
5.9.Undefined( 1 ) 5.21.toPrecision( 1 ) 
5.10.valueOf( 2 ) 5.22.toSource( 1 ) 
5.11.Maximum Minimum Values( 1 ) 5.23.toString( 1 ) 
5.12.MAX_VALUE( 1 ) 
6.String
6.1.Introduction( 3 ) 6.21.match( 1 ) 
6.2.String comparisons( 5 ) 6.22.prototype( 1 ) 
6.3.String Constructors( 1 ) 6.23.replace( 2 ) 
6.4.String Declaration( 2 ) 6.24.search( 1 ) 
6.5.anchor( 1 ) 6.25.slice( 1 ) 
6.6.big( 1 ) 6.26.small( 1 ) 
6.7.blink( 1 ) 6.27.split( 4 ) 
6.8.bold( 1 ) 6.28.strike( 1 ) 
6.9.charAt( 3 ) 6.29.sub( 1 ) 
6.10.charCodeAt( 1 ) 6.30.substr( 2 ) 
6.11.concat( 1 ) 6.31.substring( 2 ) 
6.12.fixed( 1 ) 6.32.sup( 1 ) 
6.13.fontcolor( 1 ) 6.33.toLowerCase( 1 ) 
6.14.fontsize( 1 ) 6.34.toSource( 1 ) 
6.15.fromCharCode( 1 ) 6.35.toString( 1 ) 
6.16.indexOf( 3 ) 6.36.toUpperCase( 2 ) 
6.17.italics( 1 ) 6.37.valueOf( 1 ) 
6.18.lastIndexOf( 1 ) 6.38.Words( 3 ) 
6.19.length( 2 ) 6.39.StringBuffer( 1 ) 
6.20.link( 1 ) 
7.Function
7.1.Function Definition( 5 ) 7.5.Function Call( 6 ) 
7.2.Function Object( 9 ) 7.6.function keyword( 1 ) 
7.3.Function Parameters( 6 ) 7.7.Function Return( 5 ) 
7.4.arguments( 7 ) 7.8.Dynamic Function( 1 ) 
8.Global
8.1.Introduction( 1 ) 8.7.isFinite( 1 ) 
8.2.escape( 2 ) 8.8.isNaN( 2 ) 
8.3.eval( 1 ) 8.9.NaN( 1 ) 
8.4.export( 1 ) 8.10.parseFloat( 1 ) 
8.5.import( 1 ) 8.11.parseInt( 3 ) 
8.6.Infinity( 1 ) 8.12.unescape( 1 ) 
9.Math
9.1.Introduction( 1 ) 9.16.LOG2E( 2 ) 
9.2.abs( 1 ) 9.17.max( 4 ) 
9.3.acos( 1 ) 9.18.min( 4 ) 
9.4.asin( 1 ) 9.19.PI( 3 ) 
9.5.atan( 1 ) 9.20.pow( 1 ) 
9.6.atan2( 1 ) 9.21.random( 6 ) 
9.7.ceil( 1 ) 9.22.round( 3 ) 
9.8.cos( 1 ) 9.23.sin( 1 ) 
9.9.E( 2 ) 9.24.sqrt( 1 ) 
9.10.exp( 1 ) 9.25.SQRT1_2( 2 ) 
9.11.floor( 1 ) 9.26.SQRT2( 2 ) 
9.12.LN10( 2 ) 9.27.tan( 1 ) 
9.13.LN2( 2 ) 9.28.toSource( 1 ) 
9.14.log( 1 ) 9.29.toString( 1 ) 
9.15.LOG10E( 1 ) 
10.Form
10.1.Introduction( 8 ) 10.15.Text TextField( 14 ) 
10.2.Form Object( 15 ) 10.16.TextArea( 17 ) 
10.3.Element Type( 1 ) 10.17.Action( 2 ) 
10.4.Elements( 5 ) 10.18.enctype( 1 ) 
10.5.this( 1 ) 10.19.Focus( 1 ) 
10.6.Button( 15 ) 10.20.Hidden Object( 5 ) 
10.7.CheckBox( 19 ) 10.21.Length( 1 ) 
10.8.FileUpload( 14 ) 10.22.Method( 2 ) 
10.9.Option Object( 5 ) 10.23.Name( 1 ) 
10.10.Password( 13 ) 10.24.onSubmit( 1 ) 
10.11.Radio Button( 18 ) 10.25.Reset( 13 ) 
10.12.Select( 18 ) 10.26.submit button( 14 ) 
10.13.select option( 7 ) 10.27.Form Validation( 1 ) 
10.14.Text Object( 12 ) 
11.Array
11.1.Introduction( 11 ) 11.19.map( 2 ) 
11.2.Array Declaration( 7 ) 11.20.Pop( 3 ) 
11.3.Array Index( 5 ) 11.21.prototype( 1 ) 
11.4.Array Length( 6 ) 11.22.Push( 3 ) 
11.5.Array Loop( 5 ) 11.23.remove( 1 ) 
11.6.Multi Dimensional Array( 2 ) 11.24.removeAt( 1 ) 
11.7.String Indexer( 2 ) 11.25.Reverse( 2 ) 
11.8.Clone( 1 ) 11.26.Shift( 3 ) 
11.9.Concat( 3 ) 11.27.Slice( 3 ) 
11.10.contains( 1 ) 11.28.some( 1 ) 
11.11.Every( 1 ) 11.29.Sort( 8 ) 
11.12.filter( 1 ) 11.30.Splice( 6 ) 
11.13.forEach( 2 ) 11.31.Stack( 2 ) 
11.14.indexOf( 2 ) 11.32.sum( 3 ) 
11.15.insertAt( 1 ) 11.33.toSource( 2 ) 
11.16.insertBefore( 1 ) 11.34.toString( 1 ) 
11.17.Join( 3 ) 11.35.unshift( 4 ) 
11.18.lastIndexOf( 2 ) 11.36.valueOf( 2 ) 
12.Date
12.1.Introduction( 1 ) 12.25.prototype( 1 ) 
12.2.Date constructors( 2 ) 12.26.setDate( 1 ) 
12.3.Date Calculation( 2 ) 12.27.setFullYear( 1 ) 
12.4.Date Display( 1 ) 12.28.setHours( 1 ) 
12.5.getDate( 1 ) 12.29.setMilliseconds( 1 ) 
12.6.getDay( 3 ) 12.30.setMinutes( 1 ) 
12.7.getFullYear( 2 ) 12.31.setMonth( 1 ) 
12.8.getHours( 1 ) 12.32.setSeconds( 1 ) 
12.9.getMilliseconds( 1 ) 12.33.setTime( 1 ) 
12.10.getMinutes( 2 ) 12.34.setUTCDate( 1 ) 
12.11.getMonth( 3 ) 12.35.setUTCFullYear( 1 ) 
12.12.getSeconds( 1 ) 12.36.setUTCHours( 1 ) 
12.13.getTime( 1 ) 12.37.setUTCMilliseconds( 1 ) 
12.14.getTimezoneOffset( 2 ) 12.38.setUTCMinutes( 1 ) 
12.15.getUTCDate( 1 ) 12.39.setUTCMonth( 1 ) 
12.16.getUTCDay( 1 ) 12.40.setUTCSeconds( 1 ) 
12.17.getUTCFullYear( 1 ) 12.41.setYear( 1 ) 
12.18.getUTCHours( 1 ) 12.42.toGMTString( 1 ) 
12.19.getUTCMilliseconds( 1 ) 12.43.toLocaleString( 1 ) 
12.20.getUTCMinutes( 1 ) 12.44.toSource( 1 ) 
12.21.getUTCMonth( 1 ) 12.45.toString( 1 ) 
12.22.getUTCSeconds( 1 ) 12.46.toUTCString( 1 ) 
12.23.getYear( 1 ) 12.47.UTC( 1 ) 
12.24.parse( 2 ) 12.48.valueOf( 1 ) 
13.Dialogs
13.1.alert dialog( 6 ) 13.3.prompt( 3 ) 
13.2.confirm( 4 ) 
14.Document
14.1.Introduction( 2 ) 14.20.onclick( 2 ) 
14.2.alinkColor( 2 ) 14.21.ondblclick( 1 ) 
14.3.all( 5 ) 14.22.onkeydown( 1 ) 
14.4.anchors( 2 ) 14.23.onkeypress( 2 ) 
14.5.applets( 3 ) 14.24.onkeyup( 1 ) 
14.6.bgColor( 2 ) 14.25.onload( 1 ) 
14.7.captureEvents( 1 ) 14.26.onmousedown( 1 ) 
14.8.close( 1 ) 14.27.onmouseup( 1 ) 
14.9.cookie( 1 ) 14.28.onunload( 2 ) 
14.10.domain( 1 ) 14.29.open( 1 ) 
14.11.embeds( 2 ) 14.30.Plugin( 6 ) 
14.12.fgColor( 2 ) 14.31.plugins( 2 ) 
14.13.forms( 3 ) 14.32.referrer( 1 ) 
14.14.getSelection( 1 ) 14.33.Tag Reference( 2 ) 
14.15.images( 2 ) 14.34.title( 2 ) 
14.16.lastModified( 2 ) 14.35.URL( 1 ) 
14.17.linkColor( 2 ) 14.36.vlinkColor( 2 ) 
14.18.links( 4 ) 14.37.write( 8 ) 
14.19.MimeType( 5 ) 
15.Event
15.1.Event Object( 16 ) 15.7.Key Event( 12 ) 
15.2.Event Parameter( 4 ) 15.8.Mouse Event( 19 ) 
15.3.Event Type( 7 ) 15.9.Timer Event( 2 ) 
15.4.returnValue( 1 ) 15.10.Custom Event( 1 ) 
15.5.srcElement( 2 ) 15.11.zEvents( 3 ) 
15.6.Target( 4 ) 15.12.Event Handler( 10 ) 
16.Location
16.1.Location( 16 ) 
17.Navigator
17.1.Navigator Object( 17 ) 17.5.platform( 1 ) 
17.2.appName( 2 ) 17.6.plugins( 1 ) 
17.3.javaEnabled( 1 ) 17.7.userAgent( 2 ) 
17.4.mimeTypes( 1 ) 
18.Screen
18.1.Screen Object( 9 ) 18.2.Resolution( 1 ) 
19.Window
19.1.Introduction( 4 ) 19.9.onload( 2 ) 
19.2.Window Object( 59 ) 19.10.onresize( 1 ) 
19.3.close( 1 ) 19.11.onscroll( 1 ) 
19.4.location( 1 ) 19.12.open( 8 ) 
19.5.moveBy( 1 ) 19.13.scrollBy( 1 ) 
19.6.moveTo( 1 ) 19.14.setTimeout( 1 ) 
19.7.navigator( 1 ) 19.15.Status Bar( 3 ) 
19.8.onerror( 6 ) 
20.History
20.1.History( 10 ) 
21.HTML Tags
21.1.a link( 29 ) 21.9.img( 19 ) 
21.2.Anchor( 5 ) 21.10.removeAttribute( 1 ) 
21.3.Applet( 2 ) 21.11.setAttribute( 1 ) 
21.4.Area( 13 ) 21.12.Table Sorter( 1 ) 
21.5.body( 10 ) 21.13.Table( 2 ) 
21.6.DIV( 1 ) 21.14.td( 4 ) 
21.7.embed( 1 ) 21.15.this( 1 ) 
21.8.frameset( 7 ) 21.16.iframe( 1 ) 
22.Style
22.1.backgroundColor( 3 ) 22.13.setProperty( 1 ) 
22.2.Color( 2 ) 22.14.textDecoration( 3 ) 
22.3.Computed Style( 1 ) 22.15.top( 2 ) 
22.4.cssText( 1 ) 22.16.border( 1 ) 
22.5.currentStyle( 3 ) 22.17.font( 6 ) 
22.6.display( 1 ) 22.18.height( 1 ) 
22.7.getPropertyValue( 1 ) 22.19.lineHeight( 1 ) 
22.8.item( 1 ) 22.20.paddingLeft( 1 ) 
22.9.left( 2 ) 22.21.paddingTop( 1 ) 
22.10.pixelLeft( 1 ) 22.22.postion( 1 ) 
22.11.pixelTop( 1 ) 22.23.width( 1 ) 
22.12.removeProperty( 1 ) 
23.DOM Node
23.1.Introduction( 4 ) 23.12.innerText( 2 ) 
23.2.Append( 2 ) 23.13.Insert( 1 ) 
23.3.clone( 1 ) 23.14.nextNode( 1 ) 
23.4.createDocumentFragment( 1 ) 23.15.NodeFilter( 1 ) 
23.5.createElement( 2 ) 23.16.outerHTML( 1 ) 
23.6.createTextNode( 1 ) 23.17.outerText( 2 ) 
23.7.DOM Range( 1 ) 23.18.parentNode( 1 ) 
23.8.Extract Contents( 1 ) 23.19.Remove( 1 ) 
23.9.getElementById( 1 ) 23.20.Replace( 1 ) 
23.10.getElementsByTagName( 1 ) 23.21.Text Range( 6 ) 
23.11.innerHTML( 4 ) 23.22.TreeWalker( 2 ) 
24.Drag Drop
24.1.Drag Drop Event( 8 ) 24.6.ondragleave( 1 ) 
24.2.Drag Drop( 2 ) 24.7.ondragover( 1 ) 
24.3.ondrag( 1 ) 24.8.ondragstart( 1 ) 
24.4.ondragend( 1 ) 24.9.ondrop( 1 ) 
24.5.ondragenter( 1 ) 
25.Object Oriented
25.1.Introduction( 3 ) 25.7.this( 1 ) 
25.2.Object( 11 ) 25.8.Combination( 2 ) 
25.3.Constructor( 6 ) 25.9.Inheritance( 16 ) 
25.4.Member Function( 7 ) 25.10.instanceof( 1 ) 
25.5.Properties( 3 ) 25.11.zInherit( 4 ) 
25.6.prototype( 10 ) 
26.Regular Expressions
26.1.Introduction( 6 ) 26.5.Filter( 4 ) 
26.2.Credit Card( 4 ) 26.6.Match( 9 ) 
26.3.Date( 2 ) 26.7.RegExp Object( 21 ) 
26.4.EMail( 3 ) 26.8.URL( 1 ) 
27.XML
27.1.DOM( 1 ) 
28.GUI Components
28.1.Autocomplete Textbox( 1 ) 28.3.Table Sorter( 7 ) 
28.2.Menu( 1 ) 28.4.Tooltips( 1 ) 
29.Dojo toolkit
29.1.dojo basics( 5 ) 29.50.Text Editor( 4 ) 
29.2.addOnLoad( 1 ) 29.51.TextArea( 2 ) 
29.3.behavior( 3 ) 29.52.TextBox( 7 ) 
29.4.body( 1 ) 29.53.ValidationTextBox( 8 ) 
29.5.byId( 2 ) 29.54.DateTextBox( 6 ) 
29.6.clone( 2 ) 29.55.ComboBox( 6 ) 
29.7.connect( 5 ) 29.56.ComboButton( 3 ) 
29.8.disconnect( 1 ) 29.57.CurrencyTextBox( 3 ) 
29.9.every( 2 ) 29.58.NumberSpinner( 8 ) 
29.10.exist( 4 ) 29.59.NumberTextBox( 3 ) 
29.11.some( 2 ) 29.60.Menu( 3 ) 
29.12.filter( 1 ) 29.61.Popup Context Menu( 2 ) 
29.13.firebug console( 1 ) 29.62.ProgressBar( 6 ) 
29.14.foreach( 3 ) 29.63.Slider( 11 ) 
29.15.iframe( 1 ) 29.64.DropDownButton( 1 ) 
29.16.isDescendant( 2 ) 29.65.Accordion Pane( 5 ) 
29.17.isFunction( 1 ) 29.66.Dialog( 9 ) 
29.18.isInRange( 1 ) 29.67.InlineEditBox( 4 ) 
29.19.isObject( 1 ) 29.68.ColorPicker( 1 ) 
29.20.map( 2 ) 29.69.ColorPalette( 5 ) 
29.21.query( 7 ) 29.70.TimeTextBox( 2 ) 
29.22.regexp( 3 ) 29.71.TitlePane Disclosure( 4 ) 
29.23.registerModulePath( 1 ) 29.72.Toaster( 3 ) 
29.24.sprintf( 4 ) 29.73.ToggleButton( 3 ) 
29.25.setObject( 1 ) 29.74.ToolBar( 3 ) 
29.26.setSelectable( 2 ) 29.75.ToolTip( 3 ) 
29.27.stopEvent( 1 ) 29.76.TooltipDialog( 1 ) 
29.28.subscribe( 2 ) 29.77.Tree( 1 ) 
29.29.String( 13 ) 29.78.FilteringSelect( 2 ) 
29.30.StringBuilder( 5 ) 29.79.Fisheye( 2 ) 
29.31.Array( 8 ) 29.80.Rich Text Editor( 2 ) 
29.32.ArrayList( 12 ) 29.81.TabContainer( 7 ) 
29.33.Dictionary( 10 ) 29.82.BorderLayout( 4 ) 
29.34.Stack( 6 ) 29.83.LayoutContainer( 1 ) 
29.35.Math( 7 ) 29.84.Stack Container( 4 ) 
29.36.Number( 1 ) 29.85.SplitPane( 2 ) 
29.37.Calendar( 3 ) 29.86.Animation( 26 ) 
29.38.Color( 14 ) 29.87.Canvas Draw( 9 ) 
29.39.Cookie( 1 ) 29.88.coords( 1 ) 
29.40.Date( 10 ) 29.89.Browser History( 1 ) 
29.41.I18N Locale( 3 ) 29.90.Drag Drop( 6 ) 
29.42.objectToQuery( 1 ) 29.91.Icon( 4 ) 
29.43.place( 1 ) 29.92.JSON( 3 ) 
29.44.Class Definition( 3 ) 29.93.Sequence( 1 ) 
29.45.Currency Format( 3 ) 29.94.Style Class( 10 ) 
29.46.Button( 5 ) 29.95.Timer( 1 ) 
29.47.RadioButton( 2 ) 29.96.Toggler( 1 ) 
29.48.CheckBox( 8 ) 29.97.UUID( 8 ) 
29.49.Calendar Control( 1 ) 29.98.Validation( 9 ) 
30.jQuery
30.1.jQuery( 7 ) 30.76.param( 1 ) 
30.2.Selector( 31 ) 30.77.parents( 9 ) 
30.3.Selector Attribute( 14 ) 30.78.position( 1 ) 
30.4.Selector children( 7 ) 30.79.post( 1 ) 
30.5.Selector even odd index( 13 ) 30.80.prepend( 7 ) 
30.6.Selector first last( 10 ) 30.81.prev( 3 ) 
30.7.Selector Form( 27 ) 30.82.prevAll( 3 ) 
30.8.Selector ID( 9 ) 30.83.queue( 2 ) 
30.9.Selector relation( 10 ) 30.84.ready( 2 ) 
30.10.Selector table( 6 ) 30.85.remove( 1 ) 
30.11.Selector tag class( 11 ) 30.86.removeAttr( 2 ) 
30.12.add( 4 ) 30.87.removeClass( 5 ) 
30.13.addClass( 6 ) 30.88.replaceAll( 4 ) 
30.14.after( 6 ) 30.89.replaceWith( 3 ) 
30.15.andSelf( 2 ) 30.90.resize( 1 ) 
30.16.append( 6 ) 30.91.scroll( 2 ) 
30.17.appendTo( 3 ) 30.92.scrollLeft( 2 ) 
30.18.attr( 12 ) 30.93.scrollTop( 2 ) 
30.19.before( 6 ) 30.94.select( 3 ) 
30.20.bind( 6 ) 30.95.show( 9 ) 
30.21.blur( 3 ) 30.96.siblings( 4 ) 
30.22.change( 2 ) 30.97.size( 1 ) 
30.23.children( 5 ) 30.98.slice( 7 ) 
30.24.click( 4 ) 30.99.slideDown( 8 ) 
30.25.clone( 5 ) 30.100.slideToggle( 8 ) 
30.26.closest( 2 ) 30.101.slideUp( 10 ) 
30.27.contains( 1 ) 30.102.split( 2 ) 
30.28.contents( 3 ) 30.103.support( 11 ) 
30.29.css function( 14 ) 30.104.text( 10 ) 
30.30.dblclick( 1 ) 30.105.this( 3 ) 
30.31.document( 5 ) 30.106.toggle( 10 ) 
30.32.each( 15 ) 30.107.toggleClass( 3 ) 
30.33.empty( 2 ) 30.108.trigger( 9 ) 
30.34.end( 1 ) 30.109.triggerHandler( 1 ) 
30.35.eq( 4 ) 30.110.trim( 1 ) 
30.36.error( 1 ) 30.111.unbind( 6 ) 
30.37.extend( 2 ) 30.112.unique( 1 ) 
30.38.fadeIn( 5 ) 30.113.unload( 2 ) 
30.39.fadeOut( 6 ) 30.114.val( 7 ) 
30.40.fadeTo( 7 ) 30.115.width( 5 ) 
30.41.filter( 10 ) 30.116.window( 2 ) 
30.42.find( 4 ) 30.117.wrap( 7 ) 
30.43.focus( 5 ) 30.118.wrapAll( 4 ) 
30.44.fx( 2 ) 30.119.wrapInner( 4 ) 
30.45.get( 4 ) 30.120.Form Button( 9 ) 
30.46.Grep( 4 ) 30.121.Form CheckBox( 4 ) 
30.47.hasClass( 2 ) 30.122.Form Controls( 11 ) 
30.48.height( 6 ) 30.123.Form RadioButton( 3 ) 
30.49.hide( 7 ) 30.124.Form Select( 7 ) 
30.50.hover( 6 ) 30.125.Form Submit( 5 ) 
30.51.html( 10 ) 30.126.Form TextBox( 8 ) 
30.52.id( 2 ) 30.127.Event click( 3 ) 
30.53.Img( 1 ) 30.128.Event Double Click( 2 ) 
30.54.inArray( 1 ) 30.129.Event Key( 8 ) 
30.55.index( 6 ) 30.130.Event Mouse( 17 ) 
30.56.innerHeight( 1 ) 30.131.Event( 15 ) 
30.57.insertAfter( 7 ) 30.132.CSS( 13 ) 
30.58.insertBefore( 2 ) 30.133.Span( 10 ) 
30.59.is( 4 ) 30.134.Paragraph( 34 ) 
30.60.isArray( 1 ) 30.135.DIV( 27 ) 
30.61.isFunction( 1 ) 30.136.UL LI( 12 ) 
30.62.Join( 3 ) 30.137.Animation( 26 ) 
30.63.length( 1 ) 30.138.Table( 21 ) 
30.64.live( 1 ) 30.139.UI Accordion( 20 ) 
30.65.load( 1 ) 30.140.UI Datepicker( 20 ) 
30.66.map( 17 ) 30.141.UI Dialog( 19 ) 
30.67.merge( 3 ) 30.142.UI Draggable( 25 ) 
30.68.next( 4 ) 30.143.UI Droppable( 12 ) 
30.69.nextAll( 3 ) 30.144.UI Effects( 18 ) 
30.70.nodeType( 1 ) 30.145.UI Progessbar( 3 ) 
30.71.not( 3 ) 30.146.UI Resizable( 14 ) 
30.72.offset( 4 ) 30.147.UI Selectable( 6 ) 
30.73.one( 2 ) 30.148.UI Slider( 13 ) 
30.74.outerHeight( 1 ) 30.149.UI Sortable( 14 ) 
30.75.outerWidth( 2 ) 30.150.UI Tab( 19 ) 
31.Animation
31.1.Clock( 2 ) 31.3.Text( 2 ) 
31.2.Status Bar( 2 ) 31.4.Timer( 2 ) 
32.MS JScript
32.1.ActiveXObject( 1 ) 32.17.jscript_build( 1 ) 
32.2.alpha( 1 ) 32.18.jscript_version( 1 ) 
32.3.cc_on( 1 ) 32.19.mac( 1 ) 
32.4.Dictionary( 10 ) 32.20.mc680x0( 1 ) 
32.5.Drive( 13 ) 32.21.PowerPC( 1 ) 
32.6.Drives( 3 ) 32.22.ScriptEngine( 1 ) 
32.7.Enumerator( 5 ) 32.23.ScriptEngineBuildVersion( 1 ) 
32.8.Error( 3 ) 32.24.ScriptEngineMajorVersion( 1 ) 
32.9.File( 15 ) 32.25.ScriptEngineMinorVersion( 1 ) 
32.10.Files( 3 ) 32.26.Scripting Engine Version( 1 ) 
32.11.FileSystemObject( 26 ) 32.27.set( 1 ) 
32.12.Folder( 19 ) 32.28.TextStream( 14 ) 
32.13.Folders( 4 ) 32.29.VBArray( 6 ) 
32.14.GetObject( 1 ) 32.30.win16( 1 ) 
32.15.if( 1 ) 32.31.win32( 1 ) 
32.16.jscript( 1 ) 32.32.x86( 1 ) 

:

html5 태그 지원 테스트

Language/CSS 2013. 2. 21. 14:12
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<title>HTML5 inputs and attribute support</title>
<meta name="keywords" content="html5, input, forms, attributes, browser support" />
<link rel="stylesheet" href="/css/core.css" />
<script src="/scripts/modernizr-1.0.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="/scripts/attr_support-min.js"></script>
</head>
<body id="input-attr-support">
<header>
<hgroup>
<h1>HTML5 inputs and attribute support</h1>
<h3 id="ua"></h3>
</hgroup>
</header>
<p>A red input (followed by frowny faces) indicates the browser does not support the input type.</p>
<table id="text-search-url-tel-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
<th>maxlength</th>
<th>pattern</th>
<th>placeholder</th>
<th>readonly</th>
<th>required</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr id="text-row">
<th><input id="text" type="text" /></th>
<th><label for="text">text</label></th>
<td id="t_autocomplete"></td>
<td id="t_autofocus"></td>
<td id="t_list"></td>
<td id="t_maxlength"></td>
<td id="t_pattern"></td>
<td id="t_placeholder"></td>
<td id="t_readonly"></td>
<td id="t_required"></td>
<td id="t_size"></td>
</tr>
<tr id="search-row">
<th><input id="search" type="search" /></th>
<th><label for="search">search</label></th>
<td id="s_autocomplete"></td>
<td id="s_autofocus"></td>
<td id="s_list"></td>
<td id="s_maxlength"></td>
<td id="s_pattern"></td>
<td id="s_placeholder"></td>
<td id="s_readonly"></td>
<td id="s_required"></td>
<td id="s_size"></td>
</tr>
<tr id="url-row">
<th><input id="url" type="url" /></th>
<th><label for="url">url</label></th>
<td id="u_autocomplete"></td>
<td id="u_autofocus"></td>
<td id="u_list"></td>
<td id="u_maxlength"></td>
<td id="u_pattern"></td>
<td id="u_placeholder"></td>
<td id="u_readonly"></td>
<td id="u_required"></td>
<td id="u_size"></td>
</tr>
<tr id="tel-row">
<th><input id="tel" type="tel" /></th>
<th><label for="tel">tel</label></th>
<td id="te_autocomplete"></td>
<td id="te_autofocus"></td>
<td id="te_list"></td>
<td id="te_maxlength"></td>
<td id="te_pattern"></td>
<td id="te_placeholder"></td>
<td id="te_readonly"></td>
<td id="te_required"></td>
<td id="te_size"></td>
</tr>
</tbody>
</table>
<table id="email-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
<th>maxlength</th>
<th>multiple</th>
<th>pattern</th>
<th>placeholder</th>
<th>readonly</th>
<th>required</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr id="email-row">
<th><input id="email" type="email" /></th>
<th><label for="email">email</label></th>
<td id="e_autocomplete"></td>
<td id="e_autofocus"></td>
<td id="e_list"></td>
<td id="e_maxlength"></td>
<td id="e_multiple"></td>
<td id="e_pattern"></td>
<td id="e_placeholder"></td>
<td id="e_readonly"></td>
<td id="e_required"></td>
<td id="e_size"></td>
</tr>
</tbody>
</table>
<table id="password-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>maxlength</th>
<th>pattern</th>
<th>placeholder</th>
<th>readonly</th>
<th>required</th>
<th>size</th>
</tr>
</thead>
<tbody>
<tr id="password-row">
<th><input id="password" type="password" /></th>
<th><label for="password">password</label></th>
<td id="p_autocomplete"></td>
<td id="p_autofocus"></td>
<td id="p_maxlength"></td>
<td id="p_pattern"></td>
<td id="p_placeholder"></td>
<td id="p_readonly"></td>
<td id="p_required"></td>
<td id="p_size"></td>
</tr>
</tbody>
</table>
<table id="datetime-date-month-week-time-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
<th>max</th>
<th>min</th>
<th>readonly</th>
<th>required</th>
<th>step</th>
</tr>
</thead>
<tbody>
<tr id="datetime-row">
<th><input id="datetime" type="datetime" /></th>
<th><label for="datetime">datetime</label></th>
<td id="dt_autocomplete"></td>
<td id="dt_autofocus"></td>
<td id="dt_list"></td>
<td id="dt_max"></td>
<td id="dt_min"></td>
<td id="dt_readonly"></td>
<td id="dt_required"></td>
<td id="dt_step"></td>
</tr>
<tr id="date-row">
<th><input id="date" type="date" /></th>
<th><label for="date">date</label></th>
<td id="d_autocomplete"></td>
<td id="d_autofocus"></td>
<td id="d_list"></td>
<td id="d_max"></td>
<td id="d_min"></td>
<td id="d_readonly"></td>
<td id="d_required"></td>
<td id="d_step"></td>
</tr>
<tr id="month-row">
<th><input id="month" type="month" /></th>
<th><label for="month">month</label></th>
<td id="m_autocomplete"></td>
<td id="m_autofocus"></td>
<td id="m_list"></td>
<td id="m_max"></td>
<td id="m_min"></td>
<td id="m_readonly"></td>
<td id="m_required"></td>
<td id="m_step"></td>
</tr>
<tr id="week-row">
<th><input id="week" type="week" /></th>
<th><label for="week">week</label></th>
<td id="w_autocomplete"></td>
<td id="w_autofocus"></td>
<td id="w_list"></td>
<td id="w_max"></td>
<td id="w_min"></td>
<td id="w_readonly"></td>
<td id="w_required"></td>
<td id="w_step"></td>
</tr>
<tr id="time-row">
<th><input id="time" type="time" /></th>
<th><label for="time">time</label></th>
<td id="ti_autocomplete"></td>
<td id="ti_autofocus"></td>
<td id="ti_list"></td>
<td id="ti_max"></td>
<td id="ti_min"></td>
<td id="ti_readonly"></td>
<td id="ti_required"></td>
<td id="ti_step"></td>
</tr>
</tbody>
</table>
<table id="datetimelocal-number-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
<th>max</th>
<th>min</th>
<th>readonly</th>
<th>required</th>
<th>step</th>
</tr>
</thead>
<tbody>
<tr id="datetimelocal-row">
<th><input id="datetime-local" type="datetime-local" /></th>
<th><label for="datetime-local">datetimelocal</label></th>
<td id="dtl_autocomplete"></td>
<td id="dtl_autofocus"></td>
<td id="dtl_list"></td>
<td id="dtl_max"></td>
<td id="dtl_min"></td>
<td id="dtl_readonly"></td>
<td id="dtl_required"></td>
<td id="dtl_step"></td>
</tr>
<tr id="number-row">
<th><input id="number" type="number" /></th>
<th><label for="number">number</label></th>
<td id="n_autocomplete"></td>
<td id="n_autofocus"></td>
<td id="n_list"></td>
<td id="n_max"></td>
<td id="n_min"></td>
<td id="n_readonly"></td>
<td id="n_required"></td>
<td id="n_step"></td>
</tr>
</tbody>
</table>
<table id="range-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
<th>max</th>
<th>min</th>
<th>step</th>
</tr>
</thead>
<tbody>
<tr id="range-row">
<th><input id="range" type="range" /></th>
<th><label for="range">range</label></th>
<td id="r_autocomplete"></td>
<td id="r_autofocus"></td>
<td id="r_list"></td>
<td id="r_max"></td>
<td id="r_min"></td>
<td id="r_step"></td>
</tr>
</tbody>
</table>
<table id="color-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autocomplete</th>
<th>autofocus</th>
<th>list</th>
</tr>
</thead>
<tbody>
<tr id="color-row">
<th><input id="color" type="color" /></th>
<th><label for="color">color</label></th>
<td id="c_autocomplete"></td>
<td id="c_autofocus"></td>
<td id="c_list"></td>
</tr>
</tbody>
</table>
<table id="checkbox-radio-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>autofocus</th>
<th>checked</th>
<th>required</th>
</tr>
</thead>
<tbody>
<tr id="checkbox-row">
<th><input id="checkbox" type="checkbox" /></th>
<th><label for="checkbox">checkbox</label></th>
<td id="cb_autofocus"></td>
<td id="cb_checked"></td>
<td id="cb_required"></td>
</tr>
<tr id="radio-row">
<th><input id="radio" type="radio" /></th>
<th><label for="radio">radio button</label></th>
<td id="rb_autofocus"></td>
<td id="rb_checked"></td>
<td id="rb_required"></td>
</tr>
</tbody>
</table>
<table id="file-upload-table">
<thead>
<tr>
<th><code>&lt;input&gt;</code></th>
<th>type</th>
<th>accept</th>
<th>autofocus</th>
<th>multiple</th>
<th>required</th>
</tr>
</thead>
<tbody>
<tr id="file-row">
<th><input id="file" type="file" /></th>
<th><label for="file">file</label></th>
<td id="f_accept"></td>
<td id="f_autofocus"></td>
<td id="f_multiple"></td>
<td id="f_required"></td>
</tr>
</tbody>
</table>
<p>See also <a href="/code/html5-forms-ui-support.html">html5 forms UI support</a> &amp; <a href="/code/html5-textarea-attribute-support.html">html5 textarea attributes support</a>.</p>
<p><a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary">Reference</a> <a href="http://gist.github.com/208473">Core Tests</a></p>
<p class="small">Copyright &copy; 2009 Michael Taylor (<a href="http://www.twitter.com/miketaylr">@miketaylr</a>) and licensed under the <a href="/code/license.txt">MIT license.</a> Special thanks to <a href="http://paulirish.com">Paul Irish</a>.</p>
<script type="text/javascript">var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));</script>
<script type="text/javascript">try {var pageTracker = _gat._getTracker("UA-1911699-3");pageTracker._trackPageview();} catch(err) {}</script>
</body>

</html>


출처 - http://miketaylr.com/code/input-type-attr.html


'Language > CSS' 카테고리의 다른 글

div로 세로 정렬 해결법 css코딩[핵]  (0) 2011.08.01
선의 모양(border-style)  (0) 2011.01.07
align="absmiddle"  (0) 2010.10.27
웹표준 준수사항  (0) 2010.10.27
CSS의 선택자  (0) 2010.10.27
:

find, filter, children

Language/jQuery 2013. 2. 19. 10:56

jQuery에서 검색 메소드 입니다.
다양한 검색 메소드들이 있지만 이 세가지 (find, filter, children) 메소드를 헷갈릴때가 있습니다.

filter : 현재 검색된 객체(집합)에서 다시 한번 검색하는 메소드
find : 현재 검색된 객체(집합)의 자손들에서 검색 하는 메소드, 자식의 레벨은 상관없습니다.
children : 현재 검색된 객체(집합)의 직속 자식만 검색하는 메소드

filter는 검색된 결과 객체 집합에서 특정 집합으로 다시 한번 검색 할때 사용합니다.
find 검색된 결과 객체 집합의 하위레벨을 다 뒤져서(자손) 검색 할때 사용 합니다.
children 검색된 결과 객체 집하의 바로 자식들만 뒤져서(자식) 검색 할때 사용합니다.



출처 - http://ddoong2.com/413

'Language > jQuery' 카테고리의 다른 글

jQuery Simulate  (0) 2014.11.17
https://code.google.com/p/jqueryjs/  (0) 2014.11.17
jquery masked plugin  (0) 2013.02.14
.get  (0) 2011.01.05
jQuery.each(object, callback function)  (0) 2010.10.25
: