效果:
json文件:
{ "books":[ {"id":1,"imgUrl":"images/ly.jpg","price":"45.00","title":"論語","publish":"人民文學出版社","num":"303","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":2,"imgUrl":"images/zy.jpg","price":"45.00","title":"中庸","publish":"人民教育出版社","num":"403","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":3,"imgUrl":"images/dx.png","price":"45.00","title":"大學","publish":"機械工業出版社","num":"503","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":4,"imgUrl":"images/mz.jpg","price":"45.00","title":"孟子","publish":"人民郵電出版社","num":"320","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":5,"imgUrl":"images/sj.jpg","price":"45.00","title":"詩經","publish":"人民文學出版社","num":"308","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":6,"imgUrl":"images/ss.jpg","price":"45.00","title":"尚書","publish":"人民文學出版社","num":"603","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":7,"imgUrl":"images/lj.jpg","price":"45.00","title":"禮記","publish":"上海人民出版社","num":"703","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":8,"imgUrl":"images/yj.jpg","price":"45.00","title":"易經","publish":"人民文學出版社","num":"803","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"}, {"id":9,"imgUrl":"images/cq.jpg","price":"45.00","title":"春秋","publish":"電子工業出版社","num":"903","desc":"崇賢館始置唐代太宗朝。1999年,李克先生及志同道合者復興其宗旨。以積累、傳播中華優秀傳統文化,提供全新國學體驗館為宏願。"} ] }
商品列表頁goodsList.js:
//請求json數據拼接字符串,並在URL傳參數id跳轉 $(function(){ $.ajax({ type:"get", url:"data/data.json", dataType:"json", success:function(res){ var str = "<ul class='con_ul'>"; $.each(res.books, function(idx,val) { str +="<li class=\"sec_li\"><a href='goodsDetail.html?booksId="+val.id+"' class='lp_li_a'><div class='lp_li_imgWrap'><img src='"+val.imgUrl+"'/></div><p class='lp_li_name'>" +val.title+"</p><p class='lp_li_price'>" +'¥'+val.price+"</p></a><li>"; }); str += "</ul>"; $('.content').append(str); },error:function(){ alert(error) } }); })
商品詳情頁goodsDetail.js:
$(function(){ //獲取url中的參數 function getUrlParam(name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //構造一個含有目標參數的正則表達式對象 var r = window.location.search.substr(1).match(reg); //匹配目標參數 if (r != null) return unescape(r[2]); return null; //返回參數值 } //接收URL中的參數booksId var id = getUrlParam('booksId'); console.log('id:'+id); $.ajax({ type:'get', url:'data/data.json', dataType:'json', success:function(res,status){ console.log(status) $.each(res.books, function(idx,val) { //根據id獲取詳情數據 if(id == val.id){ var str = "<img src='"+val.imgUrl+"'/><p>出版編號:"+val.id+"</p><p>出版社:"+val.publish+"</p><p>頁數:"+val.num+"</p><p>簡介:"+val.desc+"</p>"; console.log('index:'+idx); } $('.booksDeatail').append(str); }); } }) })
以上所述是小編給大家介紹的jQuery+Ajax請求本地數據加載商品列表頁並跳轉詳情頁,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!