原生 ajax 请求

function ajaxFn(type,url,bool) {
		var xhr = new XMLHttpRequest();
		xhr.open(type, url, bool);
		xhr.send(null);
		xhr.onreadystatechange = function() {
			if(xhr.readyState == 4) {
				console.log(xhr.responseText);
				var result = JSON.parse(xhr.responseText);
				console.log(result);
				var content = "";
				if(xhr.status == 200) {
					for(var i = 0; i < result.length; i++) {
						imgs = result[i].pic;
						texts = result[i].name;
						content += '<div class="item">' +
							'<img src="' + imgs + '"/>' +
							'<p class="intro">' + texts + '</p>' +
							'</div>'
					}
					var box = document.createElement("div");
					box.innerHTML = content;
					document.getElementsByTagName('body')[0].appendChild(box);
				}
			}
		}
	}
	ajaxFn('get','json/data.json',true);

  

posted @ 2018-07-11 09:56  adongP  阅读(141)  评论(0编辑  收藏  举报