天天看點

Ajax使用json前背景互動

前背景分離,虛拟背景傳回來的json格式資料檔案資料goodslist.json檔案如下:

[
	{"id":"01","exhibitorId":"0001","creatTime":"2017-10-2","exhibitsName":"張三","intro":"簡介"},
	{"id":"02","exhibitorId":"0001","creatTime":"2017-10-2","exhibitsName":"張三","intro":"簡介"},
	{"id":"03","exhibitorId":"0001","creatTime":"2017-10-2","exhibitsName":"張三","intro":"簡介"},
	{"id":"04","exhibitorId":"0001","creatTime":"2017-10-2","exhibitsName":"張三","intro":"簡介"}
]
           

要将上述json資料通過ajax擷取渲染到頁面表格中:

                <table >
		  <thead>
		    <tr>
		      <th>id</th>
		      <th>展品id</th>
		      <th>時間</th>
		      <th>展商姓名</th>
		      <th>詳情</th>
		    </tr> 
		  </thead>						  
		 <tbody id="goods"></tbody>
		</table>
           

注意一定要進入jQuery頭檔案:

<script type="text/javascript" src="jquery.min.js"></script>
           

ajax請求具體如下:

      $.ajax({ 
			type:"GET", 
			url:"goodslist.json", 
			dataType:"json", 
			success:function(data){ 
			 list="";
			//i表示在data中的索引位置,n表示包含的資訊的對象 
			$.each(data,function(i,result){ 
			//擷取對象中屬性
				list+="<tr>"
				list+="<td>"+result["id"]+"</td>"; 
				list+="<td>"+result["exhibitorId"]+"</td>";
				list+="<td>"+result["creatTime"]+"</td>";
				list+="<td>"+result["exhibitsName"]+"</td>";
				list+="<td>"+result["intro"]+"</td>";
				list+="</tr>";
			 }); 
				$('#goods').html(list); 
			},
                        error : function(error) {
                            alert("error");
                        }
		    });