본문 바로가기

ajax로 form 내용을 비동기로 전송하기

728x90
반응형
// 클라이언트 코드

var fdata = $("#form").serialize();
$.ajax({
    type: "POST",
    url: "process.php?"+fdata,
    contentType: "application/json; charset=utf-8",
    dataType:'json'
}).success(function(result){

     //  성공했을 때

    alert(result.d1);

}).error(function(result, status, error){
    // 에러 처리

});
//-- 서버쪽 코드

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

$return_data = array("d1" => "$data1", "d2" => "$data2");
echo json_encode($return_data); 


샘플 코드는 클라이언트에서 비동기로 form 데이터를 서버로 전송하고 넘겨 받은 자료를 그대로 클라이언트로 보내주는 간단한 형식인데 서버에서 넘겨받은 자료를 원하는대로 가공해서 사용할 수 있다.

728x90
반응형