ajax应用实例 获取各种数据

<script type="text/javascript">
			
			window.onload = function(){
				var oInp = document.getElementById("inp");
				
				oInp.onclick = function(){
					//获取text中的数据 
//					ajax("test.txt",function(data){
//						console.log(data);
//					})

					//获取数组中的数据
					
//					ajax("test2.txt",function(data){
//						//此时获取的不是数组,从服务器上取到的数据都是字符串
//						//所以要对字符串进行操作 方便取到数据
////						console.log(data);
//						var arr = eval(data);
//						alert(arr[0]);//通过eval可以将字符串变成数组
//					})
					
					//获取数组中的json数据 把获取的数据输入到li中
					var oUl = document.getElementById("ul1");
					ajax("arrjson.txt",function(data){
						//找到返回的事字符串 把字符串变成数组
						var arr = eval(data);
						//找到数据后遍历数组
						for(var i = 0 ; i <arr.length;i++ )
						{
							var oLi = document.createElement("li");
							
							oLi.innerHTML = '用户名为:<strong>'+arr[i].username+'</strong>,密码为:<i>'+arr[i].password+'</i>';
							oUl.appendChild(oLi);
						}
					})
				}
			}
			
			function ajax(url,fnusucc,fnFaild){
				try{
					var xhr = new XMLHttpRequest();
				}catch(e){
					var xhr = new ActiveXObject("Microsoft.XMLHTTP");
				}
			
			
				xhr.open("get",url,true);
				
				xhr.send()
				
				xhr.onreadystatechange = function(){
					if(xhr.readyState == 4)
					{
						if(xhr.status == 200)
						{
							fn(xhr.responseText);
						}else{
							if(fnFaild)
							{
								fnFaild(xhr.status);
							}
//							alert("Err:"+xhr.status);
						}
					}
				}
			}
		</script>

  

<input type="button" name="" id="inp" value="获取" />
		<ul id="ul1">
			
		</ul>

  

test.txt

hello world 

  

test2.txt

[1,2,3,4,5]

arrjson.txt

[{"username":"qq","password":"1234"},{"username":"as","password":"1234"},{"username":"zx","password":"1234"}]

  

原文地址:https://www.cnblogs.com/mingjixiaohui/p/5247114.html