在HTML表中显示JSON数据 [英] Display JSON Data in HTML Table

查看:313
本文介绍了在HTML表中显示JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器获取以下JSON字符串作为响应

I get the following JSON String from server as response

[{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]

这是我的Jquery代码

Here is my Jquery Code

$('#search').click(function() {
    alert("submit handler has fired");
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        success: function(data){ 
            alert(data);    
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});

警报正确显示JSON字符串.现在我想将此响应映射到我的表中

The alert shows the JSON String Correctly. Now i want to map this response to my table

我该怎么做??

推荐答案

尝试一下:

CSS:

.hidden{display:none;}

HTML:

<table id="table" class="hidden">
    <tr>
        <th>City</th>
        <th>Status</th>
    </tr>
</table>

JS:

$('#search').click(function() {
    $.ajax({
        type: 'POST',
        url: 'cityResults.htm',
        data: $('#cityDetails').serialize(),
        dataType:"json", //to parse string into JSON object,
        success: function(data){ 
            if(data){
                var len = data.length;
                var txt = "";
                if(len > 0){
                    for(var i=0;i<len;i++){
                        if(data[i].city && data[i].cStatus){
                            txt += "<tr><td>"+data[i].city+"</td><td>"+data[i].cStatus+"</td></tr>";
                        }
                    }
                    if(txt != ""){
                        $("#table").append(txt).removeClass("hidden");
                    }
                }
            }
        },
        error: function(jqXHR, textStatus, errorThrown){
            alert('error: ' + textStatus + ': ' + errorThrown);
        }
    });
    return false;//suppress natural form submission
});

这篇关于在HTML表中显示JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆