本文摘自PHP中文网,作者(*-*)浩,侵删。
写原生Ajax的方法:首先创建XMLHttpRequest对象;然后编写回调函数onreadystatechange;接着配置请求信息;最后发送请求即可。

Ajax(Asynchronous JavaScript and XML的缩写)是一种异步请求数据的web开发技术,对于改善用户的体验和页面性能很有帮助。
简单地说,在不需要重新刷新页面的情况下,Ajax 通过异步请求加载后台数据,并在网页上呈现出来。常见运用场景有表单验证是否登
入成功、百度搜索下拉框提示和快递单号查询等等。
想要对Ajax有一个全面的了解,这里可以去Js教程中对它进行一个全方面认识。
现在Ajax经过各种优化已经变得非常方便了,例如使用Jquery只需要一行便可以使用Ajax了。

那么原生的Ajax是什么样呢?
让我们来看一下吧。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <script type= "text/javascript" >
function ajax(url){
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject( "microsoft.XMLHttp" )
xhr.open( "get" ,url,true);
xhr.send();
xhr.onreadysattechange = () =>{
if (xhr.readystate == 4){
if (xhr.status == 200){
var data = xhr.responseTEXT;
return data;
}
}
}
}
</script>
|
readystate:
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪
status :
200: "OK"
404: 未找到页面
405:请求方式不正确
500:服务器内部错误
403:禁止请求
Ajax有两种请求方式:
get请求方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script type= "text/javascript" >
function ajax() {
xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject( "Microsoft.XMLHTTP" );
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText)
}
}
xhr.open( "get" , "/Ajax/ajax?userId=10" );
xhr.send();
}
</script>
|
post请求方式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <script type= "text/javascript" >
function ajax() {
xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject( "Microsoft.XMLHTTP" );
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText)
}
}
xhr.open( "post" , "/Ajax/ajax2" );
xhr.setRequestHeader( "content-type" , "application/x-www-form-urlencoded" )
xhr.send( "userId=10" );
}
</script>
|
以上就是原生Ajax怎么写的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
ajax异步是什么
history解决ajax出现的问题
认识 ajax
ajax 是干嘛用的?
ajax的url路径怎么写?
ajax请求的五个步骤
web 前后端怎么交互
ajax跨域的基本流程
前端请求ajax的url 路径怎么写
实例讲解h5移动开发ajax上传多张base64格式图片到服务器
更多相关阅读请进入《ajax》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » 原生Ajax怎么写