使用$ .each和.append从JSON对象构造HTML

时间:2015-06-18 22:04:03

标签: javascript jquery json

我用php调用Web Service API,响应是JSON格式,格式如下:

"hits": {
"found": 23,
"start": 0,
"hit": [
  {
    "id": "data_upload_20150608_97",
    "fields": {
      "district": "City name",
      "street": "Street name",
      "building_name": "Blue tower",
      "description": "Some description text.",
      "latlon": "0.0,0.0",
      "website": "http:\/\/www.example.com/id"
    }
}

然后使用$.getJSON检索响应,如下所示:

$("#myForm").submit(function(event) {
        event.preventDefault();
        var search_term = $("#search_txt").val()
        if(search_term.length > 0) {
            $.getJSON("assets/php/search.php?query="+search_term, function(result) {
                process_result(result);
            });
        }
    });

我想要实现的是在HTML结构中将字段与JSON分开:

<div id="result">
<div class="row">
    <div class="large-6">
        <h2>City name</h2>
        <div>District: City name</div>
        <div>Street: Street name</div>
        <div>Building name: Blue tower</div>
    </div>
    <div class="large-3">
        <div>Lat Lon: 0.0,0.0</div>
        <div>Description: Some description text.</div>
        <a href="http://www.example.com/id">Link</a>
    </div>
</div>

我已经创建了一个处理结果并显示结果的功能,但使用$.each.append并没有走得太远。我不是一个JS人,但这里是功能,看起来很混乱,甚至对我来说:

function process_result(response_string) {
        $.each(response_string, function(index, hit) {
            $("#result").append(
                $( '<div />', { 'class': 'row' } ).append(
                    $( '<div />', { 'class': 'large-6' } ).append(
                        $.each(hit, function(key, value) {
                            if(key == "District") {
                                $("#result").append("<h2>"+value+"</h2>");
                            }
                            if(key == "URL") {
                                $("#result").append("<a href="+value+">Link</a>");
                            }
                            else {
                                $("#result").append("<div>"+key+": "+value+"</div>");
                            }
                        })
                    )
                )
            )
        })
    }

这不是给我想要的结果,即。行元素打印在底部。我可能会离开这里,并且不确定是否使用$.each这里是最好的方法,但我现在没有线索。如果有人有更好的方法来解决这个问题,我很乐意听到。

另外,关于SO的第一个问题!

编辑:

我不得不放弃在PHP中处理JSON并且只将原始JSON传递给JS,然后根据需要使用以下来获取DOM结构:

function process_result(response_string) {
    var obj = JSON.parse(JSON.stringify(response_string));
    //console.log(obj.hits.hit);
    $("#result").empty();
    for(var i in obj.hits.hit){
        var item = obj.hits.hit[i]['fields'];
        var html = '';
        html += '<div class="row"><div class="large-6 columns small-12">';
        html += '<h2>'+item['district']+'</h2>';
        html += '<div>District: '+item['district']+'</div>';
        html += '<div>Street: '+item['street']+'</div>';
        html += '<div>Building: '+item['building_name']+'</div>';
        html += '</div>';
        html += '<div class="large-6 columns">';
        html += '<div>Lat Lon: '+item['latlon']+'</div>';
        html += '<div>Description: '+item['description']+'</div>';
        html += '<a href="'+item['website']+'">Link</a>';
        html += '</div>';
        $('#result').append(html);
      }
    }

2 个答案:

答案 0 :(得分:2)

一种方法:https://jsfiddle.net/Lzbt5tr1/1/

var result = '{"hits": {"found": 23,"start": 0,"hit": [{"id": "data_upload_20150608_97","fields": {"district": "City name","street": "Street name","building_name": "Blue tower","description": "Some description text.","latlon": "0.0,0.0","website": "http:\/\/www.example.com/id"}}]}}';

var obj = JSON.parse(result);
console.log(obj.hits.hit);
for(var i in obj.hits.hit){
    var item = obj.hits.hit[i]['fields'];
    var html = '';
    html += '<div class="row"><div class="large-6">';
    html += '<h2>'+item['district']+'</h2>';
    html += '<div>District: '+item['district']+'</div>';
    html += '<div>Street: '+item['street']+'</div>';
    html += '<div>Building: '+item['building_name']+'</div>';
    html += '</div>';
    html += '<div class="large-3">';
    html += '<div>Lat Lon: '+item['latlon']+'</div>';
    html += '<div>Description: '+item['description']+'</div>';
    html += '<a href="'+item['website']+'">Link</a>';
    html += '</div>';
    $('#result').append(html);
}

答案 1 :(得分:1)

你有没有考虑过使用JS模板引擎?如果没有,那么值得一看(这可能会节省你一些时间)。

请查看此posting