ajax

XMLHttpRequest
用于后台与服务器交换数据,不加载整个网页,对网页的某部分进行更新

1.创建对象
variable=new XMLHttpRequest();//创建一个对象
IE5和IE6不支持需要用ActiveXObject("Microsoft.XMLHTTP")
eg:
var xmlhttp
if(xindow.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

2.向服务器发送请求
使用XMLHttpRequest对象的open()和send()方法
open(method,url,async)
//method:"POST"/"GET"
//url:文件在服务器上的位置
//async:true(同步)/false(异步)
send(string)
setRequestHeader(header,value)来添加 HTTP 头

3.服务器响应
使用XMLHttpResponse的responseText或responseXML属性
responseText 获得字符串形式的响应数据。
responseXML 获得 XML 形式的响应数据。

4.
onreadystatechange事件
XMLHttpRequest对象的三个重要的属性:
onreadystatechange
存储函数,每当readyState改变时,就会触发 onreadystatechange 事件。
readyState
存有XMLHttpResponse的状态。从0-4变化
0:请求未初始化
1:服务器连接已建立
2:请求已接收
3:请求处理中
4:请求已完成,且响应已就绪
status
200:OK
404:未找到页面
eg:
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState=4 && xml.state==200){
document.getElementById("div1").innerHTML=xmlhttp.responseText
}
}

 

复制代码
<!DOCTYPE>
<html>
<head>
<script>
function load(){
    var httpxml;
    //创建对象
    if(window.XMLHttpRequest){
        xmlhttp=new XMLHttpRequest();
    }else{
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    //向服务器发送请求
    xmlhttp.open("GET","a.txt",true);
    xmlhttp.send();
    //服务器响应
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("div1").innerHTML=xmlhttp.responseText;
        }
    }
}
</script>
<head>
<body>
<div id="div1">show</div>
<button onclick="load()">click</button>

</body>              
复制代码

 

posted @   赵钱富贵  阅读(141)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示