javascript - Json 字符串未显示在我的 jsp 页面上

标签 javascript jquery json

在我的项目的其中一个页面中,我有这个 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.:该页面的完整代码是这样的:

https://github.com/klebermo/webapp_horario_livre/blob/master/WebContent/WEB-INF/jsp/usuario/cadastra.jsp

json 字符串从此类的“cadastra”方法发送到页面:

https://github.com/klebermo/webapp_horario_livre/blob/master/src/com/horariolivre/controller/UsuarioController.java

最佳答案

  1. 您需要使用document而不是“document”。读 docs
  2. 还将您的 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/

相关文章:

php - 为什么 jQuery.parseJSON() 不能在所有服务器上工作?

java - 如何将新的 JSONObject 添加到 json 文件中现有的 JSONArray

javascript - 从文本文件值创建 JSON 对象

javascript - 在 Karma+Jasmine 测试中读取 HTML 文件

javascript - 如何在jquery中的内部选择器回调函数中获取当前父选择器的实例

javascript - JQuery:如果现有元素 ID 不匹配,则追加新元素

javascript - 使用 Angular 形式将元素值形成为 JSON

JavaScript - 阶乘解释

javascript - 无法将 CSS 和 JavaScript 链接到 HTML

javascript - 使用模态ajax + jquery加载页面