본문 바로가기

IT노트(구)/JavaScript

자바스크립트에서 json 요청(request) 날리는 방법

결론부터 말하자면 form submit 방식으로는 한계가 있다!

html이 지원을 하지 않기 때문이다.(content type이 application/json인 상태로 post request를 날릴 수 없다! 뭔가 간단한 설정을 해주면 request header를 바꿀 수 있을 것 같지만 방법은 없다!)

따라서 결국은 ajax를 사용할 수 밖에 없다.

다음과 같은 jQuery ajax를 사용하면 json 방식의 post 요청을 간단하게 날릴 수 있다!


$.ajax({
    type: "POST",
    url: "http://www.test.com/test.jsp", // 요청할 주소
    data: {"name": "James"}, // 여기에 json을 넣어주면 된다!
    dataType: "json",
    contentType : "application/json",
    success: function(){}
});