浏览器的中的 XMLHttpRequest 对象的使用
使用XMLHttpRequest浏览器对象(IE5、IE6中是ActiveXObject对象)可以实现异步请求,Ajax就是以此为基础进行的封装.
1、同步与异步:
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url, isAsyn) {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (isAsyn) {//asynchronous
xmlhttp.onreadystatechange=myFunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
} else {//synchronous
xmlhttp.open("GET", url, false);
xmlhttp.send();
myFunc();
}
}
function myFunc() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
</script>
使用:<button type="button" onclick="loadXMLDoc('lesson1.txt',false)">通过 AJAX 改变内容</button>
2、Get与Post:
Get:参数在url中,send()参数为空 if (isAsyn) {//asynchronous
xmlhttp.onreadystatechange=myFunc;
xmlhttp.open("GET", url, true);
xmlhttp.send(); } else {//synchronous xmlhttp.open("GET", url, false); xmlhttp.send(); myFunc(); }
Post:参数在报文中 “如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定希望发送的数据:” if (isAsyn) { //asynchronous
xmlhttp.onreadystatechange=myFunc;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
} else { //synchronous
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
}

浙公网安备 33010602011771号