1. 程式人生 > >ajax中GET與POST請求

ajax中GET與POST請求

<html>
<head>
    <title>Ajax</title>
        <script language="javascript">
var xmlHttp;
// 建立 XMLHttpRequest函式
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
//傳送的json資料形式

function createQueryString() {
var name = document.getElementById('name').value;
var sex = document.getElementById('sex').value;
var queryString = "name="+ name +"&sex=" + sex;
return encodeURI(encodeURI(queryString));// 兩次編碼解決中文亂碼問題

}

function handleStateChange() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
var content = document.getElementById("content");
content.innerHTML = '';
content.innerHTML = decodeURI(xmlHttp.responseText); // 解碼
}
}

// GET 方法

function doRequestUsingGet() {
createXMLHttpRequest();
var url = "index.php?" + createQueryString() + "&time=" + new Date().getTime();
xmlHttp.open('GET', url);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}

// POST 方法
function doRequestUsingPost() {
createXMLHttpRequest();
var url = "index.php?time=" + new Date().getTime();
var queryString = createQueryString();
xmlHttp.open('POST', url);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlHttp.send(queryString);
}
</script>
    </head>
    <body>
<p>Name:<input type="text" id="name" /></p>
<p>Sex :<input type="text" id="sex" /></p>
<p><input type="button" value="GET" onClick="doRequestUsingGet()"> <input type="button" value="POST" onClick="doRequestUsingPost()"></p>
        <div id="content"></div>
     </body>

</html>

//php

<?php
header('Content-Type:text/html;Charset=GB2312');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == 'GET') {
echo "GET:".$_GET['name'].",".$_GET['sex'];
} else if ($method == 'POST') {
echo "POST:".$_POST['name'].",".$_POST['sex'];
}
?>