在我的项目的其中一个页面中,我有这个 jquery 代码,它接收两个 json 字符串,并且应该向我的表单添加一些字段:
<script>
$("document").ready(function(){
var obj_tipo = jQuery.parseJSON( "${lista_tipos}" );
var obj_campo = jQuery.parseJSON( "${lista_campos}" );
var newRow = $('<tr>');
col_1 = '<td> Tipo: </td>';
col_2 = '<td> <select name="tipo"> </select> </td> </tr>';
for(var nome in obj_tipo)
col_2.append('<option value="'+nome+'">'+nome+'</option>');
newRow.append(col_1);
newRow.append(col_2);
$("table.cadastro").append(newRow);
col_3 = '';
for(var nome in obj_campo)
col_3 += '<tr> <td> '+nome+' : </td> <td> <input type="text" name="'+nome+'" value="'+nome+'" size=20 maxlenght=40> </td> <tr>';
$("table.cadastro").append(col_3);
});
</script>
但是我的页面上没有显示任何内容。我从 Chrome 检查开发者工具,浏览器正在读取此内容:
<script>
$("document").ready(function(){
var obj_tipo = jQuery.parseJSON( "{"Tipo":[{"id":3,"nome":"gerente"},{"id":4,"nome":"supervisor"},{"id":5,"nome":"analista"},{"id":6,"nome":"tecnico"},{"id":7,"nome":"secretaria"},{"id":8,"nome":"seguranca"}]}" );
var obj_campo = jQuery.parseJSON( "{"Key":[{"id":1,"nome":"e-mail"},{"id":2,"nome":"cidade"}]}" );
var newRow = $('<tr>');
col_1 = '<td> Tipo: </td>';
col_2 = '<td> <select name="tipo"> </select> </td> </tr>';
for(var nome in obj_tipo)
col_2.append('<option value="'+nome+'">'+nome+'</option>');
newRow.append(col_1);
newRow.append(col_2);
$("table.cadastro").append(newRow);
col_3 = '';
for(var nome in obj_campo)
col_3 += '<tr> <td> '+nome+' : </td> <td> <input type="text" name="'+nome+'" value="'+nome+'" size=20 maxlenght=40> </td> <tr>';
$("table.cadastro").append(col_3);
});
</script>
有人可以指出我这段代码有什么问题吗?
ps.:该页面的完整代码是这样的:
json 字符串从此类的“cadastra”方法发送到页面:
最佳答案
- 您需要使用
document
而不是“document”
。读 docs 。 - 还将您的 json 字符串包装在
''
使用
$(document).ready(function(){
var obj_tipo = jQuery.parseJSON('${lista_tipos}' );
var obj_campo = jQuery.parseJSON( '${lista_campos}' );
......
关于javascript - Json 字符串未显示在我的 jsp 页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22932201/