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中的参数传递方法)

  • 相关阅读:
    CSS常见兼容性问题
    Ubuntu系统下创建python数据挖掘虚拟环境
    Django 模板中引用静态资源(js,css等)
    Django auth 登陆后页面跳转至/account/profile,修改跳转至其他页面
    Ubuntu14.04安装配置SVN及Trac
    禁止Chrome浏览器缓存的方法
    windows下安装配置Xampp
    Linux系统下用C语言获取MAC地址
    使用axios+formdata+vue上传图片遇到后台接受不到图片的值的问题
    使用vee-validate表单插件是如何设置中文提示?
  • 原文地址:https://www.cnblogs.com/wuxu/p/10898514.html
Copyright © 2011-2022 走看看