ajax的理解和运用

AJAX : Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

譬如微博刷新,百度输入框输入关键字后出现的推荐字。

下面列举一段代码来加深理解。

<html>
<head>
<script type="text/javascript">
var xmlhttp;

function loadXMLDoc(url,cfunc){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject){// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null){
  xmlhttp.onreadystatechange=cfunc;
  xmlhttp.open("GET",url,true);
  xmlhttp.send();
}
else{
  alert("Your browser does not support XMLHTTP.");
}

function myFunction(){
  loadXMLDoc("http://www.w3school.com.cn/ajax/demo_get2.asp?fname=Gu&lname=Xiao",function(){
     if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
      }
    });
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">通过 AJAX 改变内容</button>

</body>
</html>

XMLHttpRequest 对象的常用方法和属性:

open(method,url,async)方法:规定请求的类型、URL 以及是否异步处理请求。

send(string)方法:将请求发送到服务器。其中,string:仅用于 POST 请求。

responseText属性:获得字符串形式的响应数据。

responseXML属性:获得 XML 形式的响应数据,需解析。

onreadystatechange属性:存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。

readyState属性:存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

status属性:若返回200: "OK",若返回404: 未找到页面。

其中open函数里第一个参数一般选get,如果第三个参数选false同步的话,不需要onreadystatechange属性, 把代码放到 send() 语句后面即可,如下

xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

get:不安全 速度快 一般内容不大于2KB

post:安全 速度慢 一般内容大小没有限制  

原文地址:https://www.cnblogs.com/rhythm2014/p/3713189.html