[Javascript] Vanilla , ajax , callback, Promise, async/await 구현 예제
Code/JavaScript 2019. 7. 22. 00:11
    //vanilla ajax - callback 
    function doAjax(url, send_data, cbFunc, send_method) { 
        var xhr = new XMLHttpRequest(); 
        xhr.onreadystatechange = function() { 
            if (this.readyState == 4 && this.status == 200) { 
                cbFunc(this); 
            } 
        }; 
        send_method = send_method.toUpperCase(); 
        xhr.open(send_method, url, true); 
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
        if (send_method == 'GET') { 
            xhr.send(); 
        } else if (send_method == 'POST') { 
            xhr.send(send_data); 
        } 
    } 
    function cbFunc1(xhr) { 
        console.log('myFunction1', xhr.responseText); 
    } 
    //doAjax('/ajax/api1.php?name=qwe', '', cbFunc1, 'get'); 
    //doAjax('/ajax/api1.php', JSON.stringify({ name: 'qwe' }), cbFunc1, 'post'); 
    //============================================= 
    //vanilla js - promise
function doAjax(url, send_data, send_method) {  
    return new Promise(function(resolve, reject) {  
        var xhr = new XMLHttpRequest();  
        xhr.open(send_method, url, true);  
         
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  
        //CSRF-TOKEN 설정 
        var token = $("meta[name='csrf-token']").attr("content"); 
        //var header = $("meta[name='_csrf_header']").attr("content"); 
        xhr.setRequestHeader('X-CSRF-TOKEN', token); 
        xhr.onload = function() {  
            if (this.status >= 200 && this.status < 300) {  
                resolve( JSON.parse(xhr.response) );  //string -> object
            } else {  
                reject({  
                    status: this.status,  
                    statusText: xhr.statusText  
                });  
            }  
        };  
        xhr.onerror = function() {  
            reject({  
                status: this.status,  
                statusText: xhr.statusText  
            });  
        };  
        if (send_method.toUpperCase() == 'POST') xhr.send(send_data);  
        else xhr.send();  
    });  
} 
    
     
    //doAjax('/ajax/api1.php?name=qwe', '', 'get') 
    /* doAjax('/ajax/api1.php', JSON.stringify({ name: 'qwe' }), 'post') 
        .then(function (ret) { 
            console.log('promise 성공 = ', ret); 
        }) 
        .catch(function (err) { 
            console.error('error!', err.statusText); 
        }); */ 
//========================================================= 
// async / await 사용 
(async () => {   
    try { 
        await doAjax('/ajax/api1.php?name=qwe', '', 'get') 
            .then(function (ret) { 
            console.log('promise 성공 = ', ret); 
            }) 
            .catch(function (err) { 
             console.error('error!', err.statusText); 
            });  
    } catch(err) { //  
        console.error(err); //  
    } 
})(); 
//=========================================================
//서버측 api1.php 소스
<?php
error_reporting(E_ERROR );
ini_set('html_errors', false);
header("Content-Type: application/json; charset=UTF-8");
$method = $_SERVER['REQUEST_METHOD'];
$rt = $_REQUEST['q'];
if( $method == 'GET'){
$name = $_GET['name']??'';
}elseif( $method == 'POST'){
$jq = json_decode( key($_POST) );//json 인경우 값이 키에 있다
$name = $jq->name??'';
}
echo json_encode(array("name"=>$name.'-ret'));
'Code > JavaScript' 카테고리의 다른 글
| [Javascript] axios (ajax) (0) | 2019.07.22 | 
|---|---|
| [Javascript] fetch (ajax) (0) | 2019.07.22 | 
| [Javascript] async & await (0) | 2019.07.20 | 
| [Javascript] 클로저 , Closure (0) | 2019.07.20 | 
| [Javascript] 호이스팅(Hoisting) (0) | 2019.07.20 | 










