Ajax使用json前後臺互動
阿新 • • 發佈:2019-01-07
前後臺分離,虛擬後臺傳回來的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 border="1"> <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"); } });