AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
- GET请求
1.一个简单的get请求: <!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<script>
var loadXMLDoc = function()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// for IE7+,Ff,Chrome,...
xmlhttp = new XMLHttpRequest(); // 创建XMLHttpRequest对象
}
else
{
alert("不为老古董浏览器提供支持-.-")
}
xmlhttp.onreadystatechange=function() // 为XMLHttpRequest对象的onreadystatechange添加回调函数
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ajax/demo_test_get1",true); // open(method,url,async) async:true异步/false(同步)
xmlhttp.send(); // 仅仅在POST方式时,send带有参数
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html> 2.为了避免得到的结果是缓存中的,可以向URL中添加唯一ID: // open改为:
xmlhttp.open("GET","/ajax/demo_test_get2?t=" + Date().getTime(),true); 3.如果您希望通过 GET 方法发送信息,可以向open的URL 添加url参数 // open改为
xmlhttp.open("GET","/ajax/demo_test_get3?fname=Bill&lname=Gates",true);
- POST请求并发送数据
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<script>
var loadXMLDoc = function()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// for IE7+,...
xmlhttp = new XMLHttpRequest(); // 创建XMLHttpRequest对象
}
else
{
alert("不为老古董浏览器提供支持-.-")
}
xmlhttp.onreadystatechange=function() // 为XMLHttpRequest对象的onreadystatechange添加回调函数
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.open("POST","/ajax/demo_test_post1",async) async:true异步/false(同步)
xmlhttp.send("fname=Bill&lname=Gates");; // 仅仅在POST方式时,send带有参数
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">请求数据</button>
<div id="myDiv"></div>
</body>
</html> 上面同时也是javascript GET和POST的方式
(编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|