ajax中GET与POST请求
Posted swjieyi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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'];
?>
以上是关于ajax中GET与POST请求的主要内容,如果未能解决你的问题,请参考以下文章