AJAX请求,响应
用get发送信息
DOCTYPE html>
<html>
<body>
<h1>XMLHttpRequest 对象h1>
<button type="button" onclick="loadDoc()">请求数据button>
<p id="demo">p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/demo/demo_get2.asp?fname=Bill&lname=Gates", true);
xhttp.send();
}
script>
body>
html>
用post发送请求
DOCTYPE html>
<html>
<body>
<h1>XMLHttpRequest 对象h1>
<button type="button" onclick="loadDoc()">请求数据button>
<p id="demo">p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/demo/demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Bill&lname=Gates");
}
script>
body>
html>
异步请求就是把xhttp.open(,,true),这个函数里的第三个参数是true,
同步请求就是open函数里面的第三个参数是false(不推荐使用)
AJAX-响应
每当readystate发生变化时就会调用onreadystatechange 函数。当readyState为4 , status 为200时,响应就绪。
onreadystatechange被触发五次(0-4),每次readyState都发生变化。
如果您的网站中有多个AJAX任务,那么您应该创建一个执行XMLHttpRequest对象的函数,以及一个供每个AJAX任务的回调函数。
该函数应当包含URL以及当响应就绪时调用的函数。