【原創】ajax獲取json / $.each遍歷 / $("").html 塞到dom中

先看效果截圖:javascript

js-依賴jquery css

<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script type="text/javascript">
$(function(){
	$('#btn').on('click', function () {
        var thishtml=""
        $.ajax({
            url: 'data_list.html', //這裏直接放data_list.json也能夠
            dataType:'json',
            method: 'get',
            success: function (data) {
            	console.log(data)
				//單個獲值
				//var na = (data[0].name)
				//$(".panel").append(na);
				
				//遍歷出來    格式:jQuery.each(object, [callback])
				$.each(data,function(i,item){ 
					thishtml+="姓名:"+item["name"]+"<br>"; 			
					thishtml+="性別:"+item["sex"]+"<br>"; 
					thishtml+="郵箱:"+item["email"]+"<br>";  //strHtml反覆拿值作字符串拼接
					alert(thishtml)
					thishtml+="<hr>" 
				}) 
				//塞到頁面的dom中
				$(".panel").html(thishtml);
            },
            error:function(){ 
					alert("error!"); 
			}
        })
    })
})
</script>

data_list.html-上面的ajax取的數據源 , 其實就是一個空白的html,裏面放的jsonhtml

[ 
	{ 
	"name":"張國立", 
	"sex":"男", 
	"email":"zhangguoli@123.com" 
	}, 
	{ 
	"name":"張鐵林", 
	"sex":"男", 
	"email":"zhangtieli@123.com" 
	}, 
	{ 
	"name":"鄧婕", 
	"sex":"女", 
	"email":"zhenjie@123.com" 
	} 
]

主頁面htmljava

<input type="button" name="" id="btn" value="加載" />
<div class="panel">
</div>
相關文章
相關標籤/搜索