我从服务器获取以下JSON字符串作为响应
[{"city":"AMBALA","cStatus":"Y"},{"city":"ASANKHURD","cStatus":"Y"},{"city":"ASSANDH","cStatus":"Y"}]
这是我的jQuery代码
$('#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字符串。现在我想将此响应映射到我的表
说
我怎样才能做到这一点 ??
尝试这个:
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 });