zoukankan      html  css  js  c++  java
  • js原生的Ajax

    js原生的Ajax其实就是围绕浏览器内内置的Ajax引擎对象进行学习的,要使用js原 生的Ajax完成异步操作,有如下几个步骤:

    1)创建Ajax引擎对象

    2)为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)

    3)绑定提交地址

    4)发送请求

    5)接受响应数据

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    
    <script type="text/javascript">
    
    	function fn1(){
    		//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
    		var xmlHttp = new XMLHttpRequest();
    		//2、绑定监听 ---- 监听服务器是否已经返回相应数据
    		xmlHttp.onreadystatechange = function(){
    			if(xmlHttp.readyState==4&&xmlHttp.status==200){
    				//5、接受相应数据
    				var res = xmlHttp.responseText;
    				document.getElementById("span1").innerHTML = res;
    			}
    		}
    		//3、绑定地址
    		xmlHttp.open("GET","/WEB22/ajaxServlet?name=lisi",true);
    		//4、发送请求
    		xmlHttp.send();
    		
    	}
    	function fn2(){
    		//1、创建ajax引擎对象 ---- 所有的操作都是通过引擎对象
    		var xmlHttp = new XMLHttpRequest();
    		//2、绑定监听 ---- 监听服务器是否已经返回相应数据
    		xmlHttp.onreadystatechange = function(){
    			if(xmlHttp.readyState==4&&xmlHttp.status==200){
    				//5、接受相应数据
    				var res = xmlHttp.responseText;
    				document.getElementById("span2").innerHTML = res;
    			}
    		}
    		//3、绑定地址
    		xmlHttp.open("POST","/WEB22/ajaxServlet",false);
    		//4、发送请求
    		xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    		xmlHttp.send("name=wangwu");
    		
    	}
    
    	
    </script>
    
    </head>
    <body>
    	<input type="button" value="异步访问服务器端" onclick="fn1()"><span id="span1"></span>
    	<br>
    	<input type="button" value="同步访问服务器端" onclick="fn2()"><span id="span2"></span>
    	<br>
    	<input type="button" value="测试按钮" onclick="alert()">
    </body>
    </html>
    

      注意:

    注意:如果是post提交

    在发送请求之前设置一个头

    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    

      get请求的请求参数在open(如fn1中的参数传递方法)中或send中都可以(如fn2中的参数传递方法)

  • 相关阅读:
    elasticsearch
    CentOS6.9安装Logstash
    CentOS6.9安装Filebeat监控Nginx的访问日志发送到Kafka
    openresty capture
    CentOS6.9安装socat
    CentOS挂Windows的NFS备忘
    openCV 备忘
    rabbitmq更换数据文件和日志文件的存放位置
    根据某个文件或文件夹自制rpm包
    checkinstall打包工具使用
  • 原文地址:https://www.cnblogs.com/wuxu/p/10898514.html
Copyright © 2011-2022 走看看