Ajax-快速入门


前言

学习自w3c教程:https://www.w3cschool.cn/ajax/ajax-tutorial.html

什么是 AJAX ?

AJAX = 异步 JavaScript 和 XML。

AJAX 是一种用于创建快速动态网页的技术。

通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。

1.核心功能:XMLHttpRequest

XMLHttpRequest是AJAX的基础。

XMLHttpRequest术语缩写为XHR,中文可以解释为可扩展超文本传输请求。

XMLHttpRequest对象可以在不向服务器提交整个页面的情况下,实现局部更新网页。

XMLHttpRequest的对象用于客户端和服务器之间的异步通信。

它执行以下操作:

  • 在后台从客户端发送数据
  • 从服务器接收数据
  • 更新网页而不重新加载。

1.1创建 XMLHttpRequest 对象

1.2XMLHttpRequest常见属性

属性 描述
onreadystatechange 存储函数(或函数名),每当readyState的属性改变时,就会调用该函数。
readyState 存有的XMLHttpRequest的状态从0到4发生变化。
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
responseText 以文本形式返回响应。
responseXML 以XML格式返回响应
status 将状态返回为数字(例如,“Not Found”为404,“OK”为200)
statusText 以字符串形式返回状态(例如,“Not Found”或“OK”)

1.3XMLHttpRequest常见方法

方法 描述
abort() 取消当前请求。
getAllResponseHeaders() 以字符串形式返回完整的HTTP标头集。
getResponseHeader( headerName ) 返回指定HTTP标头的值。
void open(method,URL) 打开指定获取或交的方法和URL的请求。
void open(method,URL,async) 与上面相同,但指定异步或不。
void open(method,URL,async,userName,password) 与上面相同,但指定用户名和密码。
void send(content) 发送获取请求。
setRequestHeader( label,value) 将标签/值对添加到要发送的HTTP标头。

2.AJAX如何工作?

简而言之:XMLHttpRequest发出请求->服务器返回数据

2.1创建XMLHttpRequest对象

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");
  }

2.2 向服务器发出请求

xmlhttp.open("GET","getInfo",true);
xmlhttp.send();

2.3接收返回数据

2.3.1服务器返回String

console.log(xmlhttp.responseText);

2.3.2服务器返回xml

xmlDoc=xmlhttp.responseXML;

2.4封装成函数

<script>
function getInfo(){
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.open("GET","getInfo",true);
xmlhttp.send();

console.log(xmlhttp.responseText)

}


</script>
posted @ 2023-01-24 19:17  对CSDN使用炎拳吧  阅读(15)  评论(0编辑  收藏  举报