重复包含json数据的附加html

时间:2016-02-05 18:41:53

标签: javascript jquery html json

这对我来说是一个学习练习,所以请原谅我即将呈现的代码。我相信它会更好。在下面的代码中,您将看到我已成功创建了一个可以提取格式正确的JSON数据的变量。然后,我创建一个附加一个html块的函数。在该追加中,我引用了要显示的特定JSON数据。

HTML

<table id="jobSearchResults" bgcolor="white" style="border: 1px solid #ddd;width:100%;">
  <tbody>  
  </tbody> 
</table>

的Javascript

var json = (function () {
            var json = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': "../data/jobSearchResults.json",
                'dataType': "json",
                'success': function (data) {
                    json = data;
                }
            });
            return json;
        })(); 

$(jobSearchResults).each(function(index, element){
  $('#jobSearchResults').append('<tr><th><div style="background-color:#ddd;height:55px;width:80px;"><img src="" style="height:55px;width:80px;"></div></th><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].job_header+' </h4> '+json[0].specialty_name+', '+json[0].facility_name+' </td><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].city+',  '+json[0].state_name+' </h4> United States </td><td class="text-right"></td></tr>');       
});

现在,我需要通过使该表行重复X次并使每个新行的JSON记录号递增来使问题复杂化。在这种情况下,我既对如何采用我所写的内容感兴趣,又对其进行了扩展以包含这一新功能,而且我也感兴趣的是,如果我更有效地编写这个问题,那么更简洁的方法来解决这个问题。

2 个答案:

答案 0 :(得分:1)

jQuery&#39; each的回调函数传递了两个值。它们分别代表当前迭代的索引和值。您可以使用其中任何一个来引用原始JSON数据并相应地输出每一行。

  

$ .each()函数可用于迭代任何集合,无论它是对象还是数组。对于数组,每次都会向回调传递一个数组索引和相应的数组值。

$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

在下面的示例中,我在json变量上进行迭代,该变量包含从AJAX调用返回的JSON数据。在此上下文中,您可以使用索引来引用当前迭代(例如json[index].job_header)或直接使用该值(例如job.job_header)。

&#13;
&#13;
function displayData(json) {
  
  var $resultDisplay = jQuery('#jobSearchResults tbody');
  
  if (!json) {        
    // variable is false. there was an ajax error.
    $resultDisplay.html('<tr><td>There was an error.</td></tr>');        
  } else if (jQuery.isEmptyObject(json)) {        
    // variable is an empty object. no records were returned.
    $resultDisplay.html('<tr><td>No data to display.</td></tr>');        
  } else {
    
    // display the returned records.
    $resultDisplay.empty();
    jQuery.each(json, function(index, job) {
      $resultDisplay.append('<tr>' +
        '<td><div class="row-img"><img src="" alt=""></div></td>' +
        '<td><h4>' + job.job_header + '</h4>' + job.specialty_name + ', ' + job.facility_name + '</td>' +
        '<td><h4>' + job.city + ',  ' + job.state_name + ' </h4>United States</td>' +
        '</tr>');
    });
    
  }
  
}

jQuery.ajax({
    'url': "https://epearson001.github.io/prototype-web-application/assets/data/jobSearchResults.json",
    'dataType': "json"
  })
  .done(function(data) {
    displayData(data);
  })
  .fail(function() {
    displayData(false);
  });
&#13;
#jobSearchResults {
  border: 1px solid #ddd;
  width: 100%;
  background-color: white;
}
div.row-img {
  background-color: #ddd;
  height: 55px;
  width: 80px;
}
div.row-img img {
  height: 55px;
  width: 80px;
}
h4 {
  margin-top: 0;
  margin-bottom: 2px;
  font-size: 16px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="jobSearchResults">
  <tbody>
    <tr>
      <td>Loading data...</td>
    </tr>
  </tbody>
</table>
&#13;
&#13;
&#13;

修改

我还注意到您在AJAX通话中将async设置为false。这会破坏AJAX的异步功能,除非有特殊原因,否则我建议不要这样做。我重新构建了我的示例以使用回调函数,以便在从异步AJAX调用返回数据后显示数据。我还添加了一些错误处理。我承认这可能不适合您的特定背景,但我认为我提供了这个想法。

答案 1 :(得分:0)

给出的答案绝对表明了正确的方式去做你要求的。但是,如果您也在控制服务器,我会以不同的方式处理这个问题。我没有发回JSON数据,而是发回格式化的HTML并使用:

$('#jobSearchResults tbody').load('../data/jobSearchResults/')