Ajax技术-前后端交互

Ajax 并不是一门编程语言,而是一种前后端交互的技术

什么是 Ajax

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

Ajax 实例

<script>
	function loadXMlDoc(){
		// Ajax 脚本执行
	}
</script>

XMLHttpRequest 对象

所有现代浏览器均支持 XMLHttpRequest 对象

XMLHttpRequest 用于在后台与服务器进行数据交换

创建 XMLHttpRequest 对象

var xmlhttp = new XMLHttpRequest();

Ajax 向服务器发出请求

xmlhttp.open('GET','test.php',true);
xmlhttp.send();

方法

  • open(method,url,async)
    • method:请求的类型 GET 或 POST
    • url : 文件在服务器上的位置
    • async:true(异步)或 false (同步)
  • send(string)
    • string 仅用于 POST 请求

GET 请求

xmlhttp.open("GET","test.php?id=1",true);
xmlhttp.send();

POST 请求

xmlhttp.open("POST","test.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name=lixiney&password=hello");
  • setRequestHeader(header,value)
    • header 请求头
    • 请求头的值

Async=true

当 async = true 时

<script>
	function loadXMLDoc(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
            if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","test.php",true);
        xmlhttp.send();
    }
</script>

Ajax 服务器的响应

服务器响应

  • responseText
    • 获得字符串形式的响应数据
  • responseXML
    • 获得XML形式的响应数据

Ajax - onreadystatechange 事件

当请求被发送到服务器时,我们需要执行基于响应的任务。

每当 readyState 改变时,就会出发 onreadystatechange 事件。

  • readyState 属性存有 XMLHttpRequest 的状态信息
    • 0 : 请求未初始化
    • 1:服务器连接已建立
    • 2:请求已接收
    • 3:请求处理中
    • 4:请求已完成,且响应就绪
  • status

Ajax - Json

<script>
    function putJson(){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function(){
        	if(xmlhttp.status == 200 && xmlhttp.readyState ==4){
            	var myArr = JSON.parse(this.responseText);
                myFunc(myArr);
           	}
        }
        xmlhttp.open("GET","test.json",true);
        xmlhttp.setRequestHeader("Content-type","application/json;charset=utf-8");
        xmlhttp.send();
    }
    function myFunc(arr){
		var out = "";
        var i;
        for(i=0;i<arr.length;i++){
			out += 'a< href="'+arr[i].url+'">'+arr[i].title+'</a><br>';
        }
        document.getElementById('myDiv').innerHTML=out;
    }
</script>

test.json

[
  {
    "title": "JavaScript 教程",
    "url": "https://www.runoob.com/js/"
  },
  {
    "title": "HTML 教程",
    "url": "https://www.runoob.com/html/"
  },
  {
    "title": "CSS 教程",
    "url": "https://www.runoob.com/css/"
  }
]

Ajax技术-前后端交互
https://blog.lixey.top/Ajax技术-前后端交互/
Author
Lixiney
Posted on
July 31, 2025
Licensed under