function doFetch(url, data, method) {

        var option = {
            method: method,
            
            mode: 'same-origin',  //default: same-origin
            credentials: 'same-origin',    //default: omit
            cache: 'no-cache',    //default: default            
            redirect: 'follow', //default: follow
            referrer: 'client',   //default: client
            headers: new Headers(),
            
        }
        if( method =="POST" ){
            option.body = _data;
        }
        
        option.headers.append('Content-Type', "application/x-www-form-urlencoded; charset=UTF-8");

        var token = $("meta[name='csrf-token']").attr("content");

        option.headers.append('X-CSRF-TOKEN', token);

        return fetch(url, option );
    }

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

    doFetch('/ajax/api1.php', JSON.stringify({name: 'qasd'}), 'POST') 
            .then(ret => { 
                ret.json().then( json =>{ 
                    console.log('ret=', json ); 
                }) 
            }) 
            .catch(ret => { 
                console.log('catch=', ret); 
            }); 


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

// 실행시간(속도)

XMLHttpRequest, fetch, jQuery($.ajax) 모두 30ms 정도로 걸리는 시간은 차이가 없음

 

 

//===================
// 참고
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Fetch%EC%9D%98_%EC%82%AC%EC%9A%A9%EB%B2%95

//

 

반응형

'Code > JavaScript' 카테고리의 다른 글

[Vue.js] Nuxt.js  (0) 2019.07.23
[Javascript] axios (ajax)  (0) 2019.07.22
[Javascript] Vanilla , ajax , callback, Promise, async/await 구현 예제  (0) 2019.07.22
[Javascript] async & await  (0) 2019.07.20
[Javascript] 클로저 , Closure  (0) 2019.07.20
Posted by codens