JavaScript读取json文件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
	</body>
	<script type="text/javascript">
		window.onload=function(){
			var requestUrl='ids.json';
			var request = new XMLHttpRequest();
			request.open('GET',requestUrl);
			request.responseType='text';
			request.send();
			request.onload=function(){
				var idsText=request.response;
				var ids=JSON.parse(idsText);
				console.log('输出数组元素:');
				ids.forEach(function(item,index){
					console.log(index+":"+item);
				})
			}
		};
		
	</script>
</html>

ids.json:

[
    "11",
    "22",
    "33",
	"44",
	"55"
]

//加上错误处理

try{
			window.onload=function(){
				var requestUrl='ids.json';
				var request = new XMLHttpRequest();
				request.open('GET',requestUrl);
				request.responseType='text';
				request.send();
				request.onload=function(){
					var idsText=request.response;
					var ids=JSON.parse(idsText);
					console.log('输出数组元素:');
					ids.forEach(function(item,index){
						console.log(index+":"+item);
					})
				}
			};
		}catch(e){
			
		}
		console.log('I can run here');

 

posted @ 2019-11-08 20:20  星空天宇  阅读(587)  评论(0编辑  收藏  举报