原生Ajax怎么写

互联网 19-4-30

写原生Ajax的方法:首先创建XMLHttpRequest对象;然后编写回调函数onreadystatechange;接着配置请求信息;最后发送请求即可。

想要对Ajax有一个全面的了解,这里可以去Js教程中对它进行一个全方面认识。

现在Ajax经过各种优化已经变得非常方便了,例如使用Jquery只需要一行便可以使用Ajax了。

那么原生的Ajax是什么样呢?

让我们来看一下吧。

 <script type="text/javascript"> 	function ajax(url){ 		//创建XMLHttpRequest对象,新版本的浏览器可以直接创建XMLHttpRequest对象,IE5或IE6没有 		//XMLHttpRequest对象,而是用的ActiveXObject对象 	       var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : ActiveXObject("microsoft.XMLHttp") 	       xhr.open("get",url,true); 	       xhr.send();//发送请求 	       xhr.onreadysattechange = () =>{ 	           if(xhr.readystate == 4){//返回存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 	               if(xhr.status == 200){//返回状态码 	                   var data = xhr.responseTEXT; 	                   return data; 	               } 	           } 	       }     	   } </script>

存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化

1: 服务器连接已建立

2: 请求已接收

3: 请求处理中

4: 请求已完成,且响应已就绪

status :

200: "OK"

404: 未找到页面

405:请求方式不正确

500:服务器内部错误

403:禁止请求

Ajax有两种请求方式:

get请求方式

<script type="text/javascript"> 	function ajax() { 		//创建核心对象 		xhr = null; 		if (window.XMLHttpRequest) {// 新版本的浏览器可以直接创建XMLHttpRequest对象 			xhr = new XMLHttpRequest(); 		} else if (window.ActiveXObject) {// IE5或IE6没有XMLHttpRequest对象 			xhr = new ActiveXObject("Microsoft.XMLHTTP"); 		} 		//编写回调函数 		xhr.onreadystatechange = function() { 			if (xhr.readyState == 4 && xhr.status == 200) { 				alert(xhr.responseText) 			} 		} 		//open设置请求方式和请求路径 		xhr.open("get", "/Ajax/ajax?userId=10");//一个url还传递了数据,后面还可以写是否同步 		//send 发送 		xhr.send(); 	} </script>

post请求方式

<script type="text/javascript"> 	function ajax() { 		//创建核心对象 		xhr = null; 		if (window.XMLHttpRequest) {// 新版本的浏览器可以直接创建XMLHttpRequest对象. 			xhr = new XMLHttpRequest(); 		} else if (window.ActiveXObject) {// IE5或IE6没有XMLHttpRequest对象 			xhr = new ActiveXObject("Microsoft.XMLHTTP"); 		} 		//编写回调函数 		xhr.onreadystatechange = function() {	 			if (xhr.readyState == 4 && xhr.status == 200) { 				alert(xhr.responseText)//警告框,显示返回的Text 			} 		} 		//open设置请求方式和请求路径 		xhr.open("post", "/Ajax/ajax2");//一个servlet,后面还可以写是否同步 		//设置请求头 		xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded") 		//send 发送 		xhr.send("userId=10"); 	} </script>

以上就是原生Ajax怎么写的详细内容,更多内容请关注技术你好其它相关文章!

来源链接:
免责声明:
1.资讯内容不构成投资建议,投资者应独立决策并自行承担风险
2.本文版权归属原作所有,仅代表作者本人观点,不代表本站的观点或立场
标签: Ajax
上一篇:php获取远程图片并下载保存到本地的方法分析 下一篇:带你轻松理解KMP算法

相关资讯