首页 > 解决方案 > 使用 AJAX 从 JSON 文件中获取数据。如何使用 jQuery 缩短代码?

问题描述

如何使用 jQuery 缩短代码?而不是手动选择每个元素,也许使用单独的函数来创建<li>元素可能是一个想法?

$.ajax({
  url: 'choosePizza.json',
  dataType: 'json',
  type: 'GET',
  success: function(choosePizzaData) {
    choosePizzaHTML(choosePizzaData);
  }
});

function choosePizzaHTML(choosePizzaInData) {
  var boxar = $('.box1_data');
  var text = "";

  /*Selecting each parameter manually and get the value from the json file and place them in a list. Is there a way to shorten this? Without having to select it manually*/

  $(choosePizzaInData[0]).each(function(index, value) {
    text += '<li>' + value.botten[0] + '</li>';
    text += '<li>' + value.botten[1] + '</li>';
  });
  boxar.html(text);

  var box2 = $('.box2_data');
  var text = "";
  $(choosePizzaInData[1]).each(function(index, value) {
    text += '<li>' + value.topping[0] + '</li>';
    text += '<li>' + value.topping[1] + '</li>';
    text += '<li>' + value.topping[2] + '</li>';
  });
  box2.html(text);
}

示例 JSON:

[ { "botten": ["Krispig", "tunn"] }, { "topping": ["kött", "kyckling", "tomat"] }, { "extra": ["Fanta", "Coca cola", "Sprite"] } ] 

标签: jqueryjsonajax

解决方案


即使没有 JQuery,您也可以使用 map 方法缩短代码:

text = choosePizzaInData[0].botten.map(function(v) { 
           return '<li>' + v + '</li>';
       }).join('');

text = choosePizzaInData[1].topping.map(function(v) { 
           return '<li>' + v + '</li>';
       }).join('');

推荐阅读