Ajax从天行数据获得图片接口

Ajax从天行数据获得图片接口插入到页面

      
<html>
<head>
	<title>Ajax 使用title>
	<meta charset="utf-8">
head>
<body>       
	<div id="myDiv"><h2>Let AJAX change this texth2>div>        
	<button type="button" onclick="loadXMLDoc()">改变文件内容button>

	
	 
	<script type="text/javascript">
		function loadXMLDoc() {
			XHR = new XMLHttpRequest();
			// 把key替换成自己的key
			XHR.open('GET', 'http://api.tianapi.com/meinv/?&key=KEY&num=50&rand=1', true);
			XHR.send();
			XHR.onreadystatechange = function() {
				if (XHR.readyState === 4 && XHR.status === 200) {
					myDiv = document.getElementById('myDiv');
					// 从天行数据那获取数据之后解码为JSON对象。
					getText = JSON.parse(XHR.responseText); 
					for (var i = 0; i < getText.newslist.length; i++) {
						createSrc = document.createElement('img');
						createSrc.setAttribute('src', getText.newslist[i].picUrl);
						createTitle = document.createElement('h1');
						titleText = document.createTextNode(getText.newslist[i].title);
						createTitle.append(titleText);
						createDescription = document.createElement('p');
						DescriptionText = document.createTextNode(getText.newslist[i].description);
						createDescription.append(DescriptionText);
						myDiv.append(createTitle, createSrc, createDescription);
					}
				}
			}
		}
	script>
body>        
html>

你可能感兴趣的:(Ajax)