了解Ajax对他的的基本内容进行一个悠闲的了解。
之前一直对Ajax不了解,在大学中也没有好好地学习一番,一直没有运用到实践中。现在学习基本的知识,填补一下那片海中的Ajax概念。
以下为整理总结的内容。
1.Ajax向服务器发送请求:
?使用XMLHttpRequest 对象的open()和send()方法;
??open(method,url,async),method:表示请求的类型有GET和POST
???
??url:文件在服务器上的位置。async:true(异步)或者false(同步)
???
??send(String):将请求发送到服务器,string仅用于POST请求
2.Ajax创建对象XMLHTTPRequest
?var xmlhttp;
?if(windows.XMLHttpRequest){
//适应浏览器:IE7+,firefox,chrome,Opera,Safari
?xmlhttp = new XMLHttpRequest();
}else{
?xmlhttp = new ActiveXobject("Microsoft.xmlHTTP");
?//适应浏览器IE6,IE5
}
3.Ajax获取服务器响应
?responseText:获得字符串形式的响应数据
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
?{// code for IE7+, Firefox, Chrome, Opera, Safari
?xmlhttp=new XMLHttpRequest();
?}
else
?{// code for IE6, IE5
?xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
?}
xmlhttp.onreadystatechange=function()
?{
?if (xmlhttp.readyState==4 && xmlhttp.status==200)
???{
????//Ajax创建的对象xmlhttp获取的是字符型数据responseText;
???document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
???}
?}
xmlhttp.open("GET","/ajax/test1.txt",true);//获取数据异步
xmlhttp.send();//将s上述open的get请求,文件位置,异步发送到服务器。
}
?
???responseXML,获取XMl形式的响应数据:
4.AJAX - onreadystatechange事件
??XMLHttpRequest对象具有的三个重要属性:
??onreadystatechange:存储函数,每当readyState属相变化时候,就会调用带函数
??readyState:描述XMLHttprequest的状态0:请求初始化,1:服务器建立连接,2:请求以接收,3:请求处理中,4:请求已完成,且响应已就绪
??status:200 表示ok,
???
??当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
???
???xmlhttp.onreadystatechange = function(){
???if(xmlhttp.readyState==4 && xmlhttp.status == 200){
?????document.getElementById("myDiv").innerHTML = xmlhttp.responseText;//获取id = ‘myDiv’的dom,发送responseText的请求类型
???}
?}
?当存在多个Ajax任务时候买简历标准函数来调用它。
?
var xmlhttp;//首先定义Ajax对象。
// 这里是ajaxde 数据请求响应函数
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
?{// code for IE7+, Firefox, Chrome, Opera, Safari
?xmlhttp=new XMLHttpRequest();
?}
else
?{// code for IE6, IE5
?xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
?}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();//发送请求
}
//简历标砖函数,调用Ajax请求,点击“myFunction”
?function Myfunction(){
???loadXMLDOC(“/ajax/test.txt”,function(){ ?//调用Ajax请求,包含数据文件位置和所需要处理的任务
??????//设置Ajax请求状态
??????if(xmlhttp.readyState ==4 && xmlhttp == 200)
??????{
?????????document.getElementById("myDiv").innerHTML=xmlhttp.responseText;//说明是myDiv的DOM发送的Ajax字符请求
??????}
????}
???)
?}
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">通过 AJAX 改变内容</button>
Ajax基础知识一。
原文地址:https://www.cnblogs.com/gdp176119/p/9406806.html