javascript - 如何通过javascript将json显示为html

标签 javascript jquery json

嗨,我想要这样的功能! http://i.stack.imgur.com/p61fq.png

当我选择第一个“选择标签”时

第二个“选择标签”显示未定义

但在这张图片中,CONSOLE 区域正是显示我想要的。

我的问题是...如何在第二个“选择标签”中显示数据?

我认为我的 javascript 有问题。

$.ajax({
    type: "POST",
      url: "dropdownServlet",
      data: dataString,
      dataType: "json",
      success: function( data, textStatus, jqXHR) {
          $("#dropdown2").html("");
            $.each(data, function(){
                $.each(this,function(){
                    $("#dropdown2").append("<option>"+data.CiytName+"</option>");   
                });
            });            
     },

这是我的 json 数据

[{"CityId":"4","CityName":"Vancouver"},{"CityId":"5","CityName":"Toronto"}]

最佳答案

您需要做的就是:

    $.each(data, function(_, ob){
        $("#dropdown2").append("<option>"+ob.CityName+"</option>");   

   });    
  1. 因为你的数据已经是[{"CityId":"4","CityName":"Vancouver"},{"CityId":"5","CityName":"Toronto"}] 你只需要使用一级 $.each 迭代和 data.CiytName 有 2 个问题,
  2. data为原始对象(不是本次迭代的对象)
  3. CiytName 有错别字。

我只是建议不要在 $.each 循环迭代中追加以减少 DOM 操作的数量,尤其是当您的 json 中有大量数据要作为选项追加时。

      var select = $('<select/>'); //Create a temp element.
        $.each(data, function(){
                select.append("<option>"+ob.CityName+"</option>");   //append to the temp element 
         });       

        $("#dropdown2").html(select.html());  //finally fill in the dropdown with your latest options.

引用$.each

关于javascript - 如何通过javascript将json显示为html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016228/

相关文章:

javascript - 在 AngularJS 1.4 中使用服务器端 JSON 数组对象作为登录详细信息

javascript - Ajax使用session时不上传文件

javascript - 使用Javascript添加和删除表中的文本框错误

javascript - 如何为边界内的 div 制作动画

jquery - 错误 div 未填充

javascript - 使用 javascript 从 json 获取数组

java json 转换时出错

Javascript:如何找到两个数字数组的差异

javascript - Swagger codegen 生成的客户端访问控制问题

javascript - 尝试将 JSON 对象解析为 HTML 表