티스토리 뷰

[ 1. XHR 1 ] (****)

 

<!DOCTYPE html>

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XHR1</title>

    <script>

        // E.target = window
        // E.type = load
        // E.listener = onload
        // E.handler = 익명함수
        window.onload = function () {

            console.clear();

            //----------------------------------------------
            // * XHR 객체의 readyState 속성값의 의미:
            //----------------------------------------------
  
            // 0 > 1 > 2 > 3 > 4 (범위값: 0 ~ 4)
            // ---------------------------------------
            // readyState              의미
            // ---------------------------------------
            //     0     XHR객체를 생성하고,초기화가 안된상태(new)
            //     1     XHR객체를 초기화한 상태(open)
            //     2     XHR객체로 요청을 보낸상태(send)
            //     3     XHR객체가 응답을 받고있는 상태(미완료)
            //     4     XHR객체가 응답을 완전히 받은 상태(완료)
            // ---------------------------------------

            //----------------------------------------------
            // * XHR 객체의 status 속성값의 의미:
            //----------------------------------------------

            // status : 200 = ok
            // status : 304 = not found

            // ==================================================

            //----------------------------------------------
            // XHR 를 이용한 동기식 요청처리
            //----------------------------------------------

            //---------------------------------------------
            // 1. var XMLHttpRequest: new () => XMLHttpRequest
            //----------------------------------------------

            // XHL 객체 생성
            var xhr = new XMLHttpRequest();

            console.log('1. xhr:', xhr);
            console.log('\t+ readyState:', xhr.readyState);
            // 초기화가 안된 상태이기에 0이 나온다.

            //----------------------------------------------
            // 2. (method) XMLHttpRequest.open(
            //      method: string,             // HTTP method: GET, POST
            //      url: string,                // action URL
            //      async: boolean,             // 동기식(false)/비동기식(true)를 결정
            //      username?: string,          // HTTP basic 인증을 위한 아이디 ( 선택 )
            //      password?: string           //                       암호 ( 선택 )
            // ): void
            //----------------------------------------------

            // 동기식, GET방식, 요청을 보내는 URL주소 지정
            // xhr.open('GET', 'http://localhost:8080/doc/persons.json?name=Yoseph&age=23', false);
            // xhr.open('POST', 'http://localhost:8080/doc/persons.json', true);

            xhr.open('GET', 'doc/persons.json', false);
            // flase로 하면, 동기식 호출이 되어서 응답이 올때까지 기다리게 된다.
            // open하면 초기화가 되기 때문에, 0에서 1로 변한다.

            // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            console.log('2. xhr:', xhr);
            console.log('\t+ readyState:', xhr.readyState);

            //----------------------------------------------
            // 3. (method) XMLHttpRequest.send(
            //      body?: Document | BodyInit
            //    ): void
            //----------------------------------------------

            // xhr.send('name=Yoseph&age=23');
            // 이렇게 하면 전송파라미터를 담아서 보내게 되고

            xhr.send();
            // 이렇게 하면 전송파라미터 없이 리쿼스트 메시지만 보내게 된다.

            // send는 요청을 보내는 메소드이다.

            console.log('3. xhr:', xhr);
            console.log('\t+ readyState:', xhr.readyState);
            // 4가 출력된다. ( XHR객체가 응답을 완전히 받은 상태(완료) )
            // 그 이유는 응답이 너무 빨리 와서 응답이 받고 있는 상태가 아닌 완전히 받은 상태로 나오게 된다.


            //----------------------------------------------
            //4. XHR로 보낸 요청과 그 응답 데이터를 이용해서,
            // --현재 문서의 <body>태그의 컨텐츠로 지정
            //----------------------------------------------

            document.body.innerHTML = xhr.responseText; // 응답데이터

            // body태그의 컨텐츠로 응답메시지의 텍스트를 받아온다.

        };  // onload

    </script>

    <link rel="shortcut icon" href="ico/favicon.ico" type="image/x-icon">
    <link rel="icon" href="ico/favicon.ico" type="image/x-icon">
    
</head>

<body>

</body>

</html>

[ 2. XHR 2 ] (****)

 

<!DOCTYPE html>

<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XHR2</title>

    <link rel="shortcut icon" href="ico/favicon.ico" type="image/x-icon">
    <link rel="icon" href="ico/favicon.ico" type="image/x-icon">

    <script>

        window.onload = function () {

            console.clear();
            
            // XHR 를 이용한 비동기식 요청처리

            //----------------------------------------------//
            // 1. var XMLHttpRequest: new () => XMLHttpRequest
            //----------------------------------------------//
            var xhr = new XMLHttpRequest();

            //----------------------------------------------//
            // 2. (property) XMLHttpRequest.onreadystatechange: 
            //              (this: XMLHttpRequest, ev: Event) => any
            //----------------------------------------------//

            xhr.onreadystatechange = function () { // (*****)
                console.log('onreadystatechange:', xhr.readyState);

                if(xhr.readyState == 4) {   // 응답완료상태에서...

                    // readyState값이 4는 응답이 완료된 상태를 의미한다.

                    if(xhr.status == 200) { // HTTP status code

                        // HTTP status code를 검사하여, 정상응답(200)인 경우에만
                        // 응답 데이터(xhr.reponseText)를 사용

                        document.body.innerHTML = xhr.responseText;

                        // JSON.parse: JSON -> JS Object 로 변환
                        var arr = JSON.parse(xhr.responseText);
                        console.log(arr);

                        if(arr.length > 0) {

                            var person = arr[0];

                            // 그룹으로 로그 묶기 ( 그룹 로그 )
                            console.group('PERSON');
                                console.log('1. id:', person.id);
                                console.log('2. first_name:', person.first_name);
                                console.log('3. last_name:', person.last_name);
                                console.log('4. email:', person.email);
                                console.log('5. gender:', person.gender);
                                console.log('6. ip_address:', person.ip_address);
                            console.groupEnd();

                        } // if(array.length)

                    } // if(status==200)

                } // if(readyState==4)
                
            };  // onreadystatechange

            //----------------------------------------------//
            // (method) XMLHttpRequest.open(
            //   method: string, url: string, async: boolean, username?: string, password?: string
            // ): void
            //----------------------------------------------//
            xhr.open('GET', 'doc/persons.json', true);

            // 필요시, 아래의 메소드를 통해서, Request Message의 헤더영역에
            // 새로운 헤더 추가 또는 기존 헤더의 값 변경
            // xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            //----------------------------------------------//
            // (method) XMLHttpRequest.send(body?: Document | BodyInit): void
            //----------------------------------------------//
            xhr.send();

        };  // onload

    </script>

</head>

<body>
    
</body>

</html>

[ 3. ajax - load( ) 메소드 (복습) ]

 

<!DOCTYPE html>
<html lang="ko">

<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax 복습1 - load() 메소드</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js" crossorigin="anonymous"></script>

    <style>

        div{
            outline: 3px double blue;
        }
        
    </style>

    <script>

        $(function(){

            $("#news1").load('news.html #news1');
            $("#news2").load('news.html #news2');
            // 각각의 요소에 해당요소를 로딩해온다.

        }); //.jq

        // 제이쿼리의 Entry Point 안에서 수행하지 않고, 밖에서 수행하면
        // 정상작동 안할 뿐만 아니라, 오류도 나지 않음 (***)

    </script>

</head>

<body>

    <h1>sample01</h1>

    <hr>

    <h3>NEWS1</h3>
    <div id="news1"></div>

    <h3>NEWS2</h3>
    <div id="news2"></div>

</body>

</html>

[ 4. serialize / param ( ) 메소드 - 복습 ]

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>복습 - serialize / parm</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        console.clear();

        $(() => {

            $("#submit").click( (e) => {

                e.preventDefault();
                // 기본 기능을 막는다.

                let serializedStr = $('#form1').serialize();
                console.log(`serializedStr : ${serializedStr}`);
                // serialize() 메소드는 <form>테그 안에 있는 데이터를 빠르게 보낼 수 있다. (*)

                let paramStr = $.param({name : "hehehe", age : 23 });
                console.log(`paraStr : ${paramStr}`);
                // param은 배열, 객체 등을 가지고 직렬화 표현을 만들어 주는 jQuery 함수이다.

            }); // onclick

        }); // .jq

    </script>

</head>

<body>

    <h1>복습 - serialize / parm</h1>

    <hr>

    <form action="#" id="form1">

        1. name: <input type="text" name="name"> <br>
        2. age: <input type="number" name="age">

        <p></p>

        <input type="submit" value="submit" id="submit">

    </form>
    
</body>

</html>

[ 5. ajax 라이프 사이클 ] (****)

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>aj03 - ajax라이프사이클</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        // script의 defer 속성을 작성하면, DOM이 완료될 때 수행되는 것이다. (***)

        console.clear();
        
        var obj = { name: 'Yoseph', age:23 };

        let queryString = $.param(obj);
        console.log(`1. queryString: ${queryString}`);

        // ajax(url: string, settings?: JQueryAjaxSettings): JQueryXHR
        $.ajax('MOCK_DATA.json', {

            // ====================================================================================

            // By default, all requests are sent asynchronously (i.e. this is set to true by default).
            // If you need synchronous requests, set this option to false.
            // Cross-domain requests and dataType: "jsonp" requests do NOT support synchronous operation.
            async: true,

            // 동기식(false)으로 할것인지, 아니면 비동기식(true)으로 할 것인지 작성한다. (****)
            // 비동기식으로 하지 않고 동기식으로 작동될 시에는 응답이 돌아올때까지 기다리게 된다.

            // ====================================================================================

            // If set to false, it will force requested pages NOT to be cached by the browser.
            // Note: Setting cache to false will only work correctly with HEAD and GET requests.
            cache: true,

            // 캐쉬를 남길지, 남기지 않을지 정하는 옵션이다.
            // false에 해야 캐쉬를 브라우저에 남기지 않으며, 캐쉬를 남기지 않는 편이 좋다.

            // ====================================================================================

            // Set a timeout (in milliseconds) for the request.
            // This will override any global timeout set with $.ajaxSetup().
            timeout: 1000,

            // 응답이 1초 안에 오지 않으면, 오류를 발생한다. (*****)

            // ====================================================================================

            // If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true.
            // This allows, for example, server-side redirection to another domain. (version added: 1.5)
            crossDomain: true,

            // ====================================================================================

            // Whether to trigger global Ajax event handlers for this request.
            // The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered.
            // This can be used to control various Ajax Events.
            global: true,

            // 전역인지, 지역인지 확인

            // ====================================================================================

            // The type of request to make ("POST" or "GET"), default is "GET".
            // Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, 
            // but they are NOT supported by all browsers.
            type: 'get',

            // 전송방식을 확인 (****)

            // ====================================================================================

            // Data to be sent to the server.
            // It is converted to a query string, if NOT already a string.
            // It's appended to the url for GET-requests.
            // See processData option to prevent this automatic processing.
            // Object must be Key/Value pairs.
            // If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting
            data: queryString,

            // 백엔드쪽으로 보낼 데이터를 의미한다. (****)

            // ====================================================================================

            // A function to be used to handle the raw response data of XMLHttpRequest.
            // This is a pre-filtering function to sanitize the response.
            // You should return the sanitized data.
            // The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
            dataFilter: (raw, dataType) => {
                console.debug('dataFilter invoked.');
                console.log('dataType:', dataType);
                console.log('raw:', raw);

                return raw;
            },

            // success에 데이터를 주기 전에, 필터링을 할 수 있게 해준다. ( 2단계 ) (****)

            // ====================================================================================

            // The type of data that you're expecting back from the server.
            // If none is specified, jQuery will try to infer it based on the MIME type of the response.

            // contentType: "application/x-www-form-urlencoded; charset=UTF-8", // default if POST method.
            dataType: "json",    // "html", "xml", "json", "text", "jsonp"

            // 서버로부터 받고자 하는 데이터의 타입을 의미한다. (****)

            // ====================================================================================

            // (method) JQueryAjaxSettings.beforeSend?(jqXHR: JQueryXHR, settings: JQueryAjaxSettings): any
            // beforeSend: () => console.debug('beforeSend invoked.'),
            beforeSend: (jqXHR, settings) => {
                console.debug('beforeSend invoked.');
                console.log('settings:', settings);
            },

            // 데이터를 전송하기 전에 수행된다. ( 1단계 )

            // ====================================================================================

            // (method) JQueryAjaxSettings.complete?(jqXHR: JQueryXHR, textStatus: string): any
            complete: (jqXHR, textStatus) => {
                console.debug('complete invoked.');
                console.log('\t+ jqXHR:', jqXHR);
                console.log(`\t+ status: ${textStatus}`);
            },

            // 완료되었을때 ( 4단계 )

            // ====================================================================================
            
            // (method) JQueryAjaxSettings.error?(jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any
            error: (jqXHR, textStatus, errorThrown) => {
                console.debug('error invoked.');
                console.log(`\t+ textStatus: ${textStatus}`);
                console.log(`\t+ errorThrown: ${errorThrown}`);
                console.log('\t+ jqXHR:', jqXHR);
            },

            // 오류가 발생했을 때 ( 3단계 )

            // ====================================================================================

            // (method) JQueryAjaxSettings.success?(data: any, textStatus: string, jqXHR: JQueryXHR): any
            success: (data, textStatus, jqXHR) => {
                console.debug('success invoked.');
                console.log(`\t+ textStatus: ${textStatus}`);
                console.log('\t+ jqXHR:', jqXHR);
                console.log('\t+ data:', data);
            },

            // 데이터가 성공적으로 주고받았을 때 ( 3단계 )

            // ====================================================================================

        }); // $.ajax
        
    </script>

</head>

<body>

    <h1>ajax 라이프 사이클(***)</h1>

    <hr>


</body>

</html>

[ 6. $.get 메소드 - get 방식으로 자원 요청 ] (****)

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ajax의 get/post( ) 메소드</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        // script defer는 DOM트리가 완료될 때까지, 스크립트 내에 있는 코드의 수행을 미루라는 것이다.
        // 옛날 브라우저를 사용하는 사용자는 defer이 먹히지 않을 수 있기에 조심해야 한다.

        // ====================================================

        console.clear();

        // ====================================================

        // 1. get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR
        // 2. get(url: string, data?: string | Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR
        // 3. get(settings: JQueryAjaxSettings): JQueryXHR

        // ====================================================

        $.get( // $.get은 get방식으로 자원을 요청할 때 사용한다.

            'persons.xml', // url 지정

            (xml) => { // xml파일을 달라고 했으니, 에로우 함수에서 매개변수로 xml지정

                console.debug('success invoked.');
                console.log(xml);

                // xml 파일을 가지고 온다.

                // ====================================================

                let persons = $(xml).find('person');
                console.log(persons);
                // xml 파일의 원소에서 person 태그를 가지고 온다.

                // ====================================================

                if(persons.length == 0) return;
                // 배열의 원소가 없으면, 끝내라.

                // ====================================================

                $.each(persons, (i, p) => {
                    // console.log(i, p)

                    let id = $(p).find('id').text()
                    let firstName = $(p).find('first_name').text()
                    let lastName = $(p).find('last_name').text()
                    let gender = $(p).find('gender').text()
                    let email = $(p).find('email').text()
                    let ipAddress = $(p).find('ip_address').text()

                    console.log(i, id, firstName, lastName, gender, email, ipAddress)

                }); // each 반복문

                // ====================================================

            }, "xml"); // dataType? : 받기를 원하는 데이터의 형식을 작성

            // ajax메소드는 제이쿼리의 entry point인 $(function(){...})이 없어도 사용이 가능하다.

    </script>

</head>

<body>

    <h1>$.get</h1>

    <hr>

</body>

</html>

[ 7. $.getJSON 메소드 - get 방식으로 json 파일을 가지고 온다. ] (******)

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>$.getJSON(*****)</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        console.clear();

        // ==========================================
        // 1. getJSON(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR
        // 2. getJSON(url: string, data?: string | Object, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR
        // ==========================================
        
        $.getJSON('MOCK_DATA.json', (json) => { // $.getJSON("url", 성공시의 함수);

            console.debug('success invoked.');
            console.log(json);

            // ==========================================

            $.each(json, (i, v) => {

                // console.log(i, v);

                let id = v.id;
                let firstName = v.first_name;
                let lastName = v.last_name;
                let gender = v.gender;
                let email = v.email;
                let ipAddress = v.ip_address;

                console.log(i, id, firstName, lastName, gender, email, ipAddress);

            }); // $.each : json에서 원소를 하나씩 빼와서, 함수 적용

        }); // $.getJSON

    </script>

</head>

<body>

    <h1>$.getJSON</h1>
    <hr>

</body>

</html>

[ 8. $.getScript 메소드 - get 방식으로 Script 파일을 가지고 온다. ]

 

<!DOCTYPE html>
<html lang="ko">

<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title> $.getScript </title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        console.clear()

        // getScript(url: string, success?: (script: string, textStatus: string, jqXHR: JQueryXHR) => any): JQueryXHR
        // 외부 자바스크립트를 불러올때 사용한다.

        // ============================================================

        // $.getScript('test.js');
        // success?을 넣으면, 성공시에 수행되는 것을 지정할 수 있으나,
        // 지정하지 않으면, 자동으로 수행된다.

        // ============================================================

        $.getScript('test.js', js => {
            console.debug('success invoked.')
            console.log(`\t+ js: ${js}`)
        }); // $.getScript

        // 이때 success만 시행되는 것이 아니라, test.js도 불러오고 success가 시행되는 것이다.

    </script>

</head>

<body>

    <h1> $.getScript </h1>
    <hr>

</body>

</html>

[ 9. $.ajaxSettings - ajax의 기본설정 알아보기 ] (*)

 

<!DOCTYPE html>
<html lang="ko">

<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ajax의 기본설정 알아보기</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        console.clear();

        console.log($.ajaxSettings);
        // $.ajaxSettings에는 ajax의 기본 세팅이 들어가 있다.
        // ajax의 기본 설정을 알아볼 수 있다.

        // console.debug($.ajaxSettings);

    </script>

</head>

<body>

    <h1>$.ajaxSettings</h1>
    <hr>

</body>

</html>

[ 10. $.ajaxSetup- ajax 기본 설정 바꾸기 ] (****)

 

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ajax의 기본 설정 바꾸기</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>

        // script defer은 DOM 트리가 완료될때까지 기다려준다. document.ready와 동일

        console.clear();

        // ajaxSetup(options: JQueryAjaxSettings): void

        $.ajaxSetup({

            async: true, // 비동기식
            cache: false, // 캐쉬를 남기지 않고
            global: true, // 전역으로
            timeout: 1000, // 1초만 기다린다.
            type: 'get', // get 방식으로 가지고 오기

            // ========================================

            headers: {
                "X-Requested-With": "XMLHttpRequest",       // Always added automatically
                "Custom-Header1": "Custom-Value1",
                "Custom-Header2": "Custom-Value2"
            },

            // ========================================

            statusCode: { // $.ajaxSetup은 각각의 statusCode의 값에 따라서 함수가 다르게 수행되게 지정할 수 있다.
                200 : () => console.debug(`HTTP status code: 200`),
                404 : () => console.debug(`HTTP status code: 404`)
            },
            
            // ========================================

            beforeSend: () => console.debug('1. beforeSend invoked.'),
            complete: () => console.debug('3. complete invoked.'),

            // ========================================

            // (method) JQueryAjaxSettings.error?(jqXHR: JQueryXHR, textStatus: string, errorThrown: string): any
            error: (jqXHR, textStatus, errorThrown) => {
                console.debug('2. error invoked.')
                console.log(`\t+ textStatus: ${textStatus}`)
                console.log(`\t+ errorThrown: ${errorThrown}`)
            }

            // ========================================

        }); // $.ajaxSetup

        // ------------------------------------- //

        // get(url: string, success?: (data: any, textStatus: string, jqXHR: JQueryXHR) => any, dataType?: string): JQueryXHR
        $.get('http://localhost:8080/persons.xml', (xml) => {
            console.debug('2. success invoked.')
            console.log('\t+ xml:', xml)

        }, 'xml');

    </script>

</head>

<body>

    <h1>$.ajaxSetup</h1>
    <hr>

</body>

</html>

[ 11. ajax의 실행순서 ]

 

<!DOCTYPE html>
<html lang="ko">

<head>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>ajax의 실행순서</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-migrate/3.4.0/jquery-migrate.min.js"></script>

    <script defer>
        
        console.clear();

        // (method) JQuery.ajaxStart(handler: () => any): JQuery
        $(document).ajaxStart( () => console.log(`1. ajaxStart`) );

        // ajaxSend(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxOptions: JQueryAjaxSettings) => any): JQuery
        $(document).ajaxSend( () => console.log(`2. ajaxSend`) );

        // ajaxStop(handler: () => any): JQuery
        $(document).ajaxStop( () => console.log(`3. ajaxStop`) );

        // ajaxComplete(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: any) => any): JQuery
        $(document).ajaxComplete( () => console.log(`4. ajaxComplete`) );

        // (method) JQuery.ajaxSuccess(handler: (event: JQueryEventObject, XMLHttpRequest: XMLHttpRequest, ajaxOptions: JQueryAjaxSettings) => any): JQuery
        $(document).ajaxSuccess( () => console.log(`5. ajaxSuccess`) );

        // ajaxError(handler: (event: JQueryEventObject, jqXHR: JQueryXHR, ajaxSettings: JQueryAjaxSettings, thrownError: any) => any): JQuery
        $(document).ajaxError( () => console.log(`6. ajaxError`) );

    </script>

</head>

<body>

    <h1>ajax의 실행순서</h1>
    <hr>

</body>

</html>

 

 

728x90
댓글
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
최근에 올라온 글
Total
Today
Yesterday
공지사항