跨域获取JSON数据并循环渲染独立HTML Div的实现方法
问题:跨域获取JSON并将每条数据渲染为独立HTML Div
通过外部站点的URL跨域获取JSON数据,需要将每条数据渲染到独立的HTML Div中,求最简单有效的实现方法。
当前代码
<script> $.ajax({ dataType: "json", url: 'https://*****************/DirectDownload/GetShopProducts?token=*********&searchString=polo', success: function(products){ var html = '<div>'; $.each(products, function (index, value) { html += '<h2>Item Code:</h2><p>' + value.ItemCode + '</p>'; }); html += '</div>'; $('#output').html(html); } }); </script>
控制台返回的JSON数据
[{ "ItemCode":"1100-M-NV-FER03EM2-FER", "Description":"Osprey Deluxe Poloshirt", "TechnicalInfo":"", "ImageName":"1100NAR.jpg", "FfProductCode":"1100-M-NV-EM2-FER", "CategoryDescription":"PoloShirts", "CategoryImage":"******.**.**/web/images/category_poloshirt.jpg" },{ "ItemCode":"1160-20-NV-FER03EM1-FER", "Description":"Wren Ladies Poloshirt", "TechnicalInfo":"", "ImageName":"1160NAR.jpeg", "FfProductCode":"1160-20-NV-EM1-FER", "CategoryDescription":"Polo Shirts", "CategoryImage":"https://******.**.**/web/images/category_poloshirt.jpg" }]
期望效果
希望每条商品数据都渲染在独立的Div中,包含所有字段信息:
<script> $.ajax({ dataType: "json", url: 'https://*****************/DirectDownload/GetShopProducts?token=*********&searchString=polo', success: function(products){ for each { <div> <h2>Item Code:</h2><p>$ItemCode</p> <h2>Description:</h2><p>$description</p> .... </div> } }); </script>
解决方案
直接修改原代码,使用模板字符串简化HTML拼接,为每条数据生成独立Div,同时完善错误处理:
$.ajax({ dataType: "json", url: 'https://*****************/DirectDownload/GetShopProducts?token=*********&searchString=polo', success: function(products){ let html = ''; // 遍历每条商品数据,生成独立的商品Div $.each(products, function (index, product) { html += ` <div class="product-card"> <h2>商品编码:</h2> <p>${product.ItemCode}</p> <h2>商品描述:</h2> <p>${product.Description}</p> <h2>产品编号:</h2> <p>${product.FfProductCode}</p> <h2>分类:</h2> <p>${product.CategoryDescription}</p> ${product.ImageName ? `<img src="https://******.**.**/web/images/${product.ImageName}" alt="${product.Description}" style="max-width:200px;">` : ''} </div> `; }); // 将拼接好的HTML插入到页面容器中 $('#output').html(html); }, error: function(xhr, status, error) { // 请求失败时给出提示 $('#output').html('<p>商品数据加载失败,请稍后重试</p>'); console.error('请求错误详情:', error); } });
关键说明:
- 模板字符串(反引号`):替代传统字符串拼接,语法更清晰,避免引号转义和拼接错误,支持多行书写。
- 独立Div结构:每条商品对应一个
.product-card的Div,方便后续通过CSS统一设置样式(比如添加边框、间距等)。 - 字段完整渲染:根据返回的JSON字段,补充了描述、产品编号、分类等信息,同时判断图片是否存在再渲染,避免无效图片标签。
- 错误处理:增加了
error回调,请求失败时页面会显示提示信息,控制台输出错误详情,便于调试。 - 跨域前提:确保目标服务器已开启CORS跨域资源共享,允许你的站点域名访问;如果服务器未配置CORS,需要改用JSONP(需服务器支持)。
内容的提问来源于stack exchange,提问作者richag
相关产品推荐
相关产品推荐

