Ajax 异步请求数据的方式有两种:GET 和 POST。
如果是 GET 模式,则直接将数据放置到异步请求的 URL 地址中,而 send() 方法不发送任何数据;
var queryString = "name=Liruxing&sex=man"; var url = "index.php" + queryString + "time=" + new Date().getTime(); xmlHttp.open('GET',url); xmlHttp.send(null);
如果是 POST 模式,则将数据放置在 send() 方法中发送。var queryString = "name=Liruxing&sex=man"; var url = "index.php" + new Date().getTime(); xmlHttp.open('POST',url); xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xmlHttp.send(queryString);
下面的示例能够更清楚的演示 GET 模式和 POST 模式的区别(Ajax 结合 PHP)
index.html
<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();
}
}
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>
index.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'];
}
?>
效果演示: