//ajax.htm


<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="utf-8">
</head>

<body>

<h2>Ajax Example</h2>
<input id="input1" type="text" value="ajax1"></input>
<button id="do_ajax" onclick="doajax();">Do Ajax</button>
<p id="status">Ready</p>
<p id="result">Result</p>

<script>
function doajax(){
    var xhr = new XMLHttpRequest();

    //콜백함수
    xhr.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {           
            document.getElementById("status").innerHTML = "Succeeded!";
            document.getElementById("result").innerHTML = this.responseText;
            console.log("성공 ", this.responseText);
            obj = JSON.parse(this.responseText);
            console.log(obj.name , obj.time);
           
        }else{
            console.log("상태 = ", this.readyState , this.status);
        }
    };
       
    var str = document.getElementById("input1").value;
    var json_data = JSON.stringify({ "id1": str });

    //GET
    /*xhr.open("GET", "server.php?q=" + json_data, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send();*/

    //POST
    xhr.open("POST", "server.php", true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("q=" + json_data);

};
/*
"Content-Type"
    "application/json"
    "text/plain;charset=UTF-8"
    'application/x-www-form-urlencoded; charset=ISO-8859-1'
    "application/x-www-form-urlencoded; charset=UTF-8."
    'text/plain; charset=ISO-8859-1'
*/

/*
readyState    
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

status    
200: "OK"
404: Page not found
*/
</script>

</body>
</html>



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

//server.php

<?php
//header("Content-Type: application/json; charset=UTF-8");
error_reporting(0);

$rt = $_REQUEST['q'];
$gt = $_GET['q'];
$pt = $_POST['q'];

//echo "서버 응답: "."REQ=[".$rt."] , "."GET=[".$gt."] , "."POST=[".$pt."] "."id2=[".$id2."]";

$jq = json_decode($pt);
$id1 = $jq->id1;
$id2 = $id1."-2";
echo json_encode(array("name"=>$id2, "time"=>"2pm"));

?>



Posted by 코덴스

댓글을 달아 주세요