테스트 사이트 - 개발 중인 베타 버전입니다

jQuery없이 네티브자바스크립트로 서버에 요청보내기4 - JSON

· 2년 전 · 572

종종 웹 개발에서 HTTP메소드로 PUT를 지정하고 JSON 타입의 헤더부를 작성하여 서버에 요청을 보내거나 결과를 받아야 할 필요가 있습니다.

jQuery로 다음과 같이 구현합니다.

[code]

$.ajax('myservice/user/1234', {

    method: 'PUT',

    contentType: 'application/json',

    processData: false,

    data: JSON.stringify({

        name: 'John Smith',

        age: 34

    })

})

.then(

    function success(userInfo) {

        // userInfo will be a JavaScript object containing properties such as

        // name, age, address, etc

    }

);

[/code]

 

그러면 네티브자바스크립트로는 어떻게 구현할까요?

[code]

var xhr = new XMLHttpRequest();

xhr.open('PUT', 'myservice/user/1234');

xhr.setRequestHeader('Content-Type', 'application/json');

xhr.onload = function() {

    if (xhr.status === 200) {

        var userInfo = JSON.parse(xhr.responseText);

    }

};

xhr.send(JSON.stringify({

    name: 'John Smith',

    age: 34

}));

[/code]

아주 명백하며 이것은 IE8에서도 잘 작동합니다.

다음시간에는 네티브자바스크립트로 파일업로드 하는 방법을 고찰하겠습니다.

댓글 작성

댓글을 작성하시려면 로그인이 필요합니다.

로그인하기

게시글 목록

번호 제목
16429
16424
16423
16412
16408
16407
16401
16395
16394
16391
16390
16389
16387
16386
JavaScript js playground
16382
16381
16377
16374
16372
16356
16355
16354
16353
16347
16346
16339
16338
16332
16331
16330