【问题标题】:How do I display values of an JSON object?如何显示 JSON 对象的值?
【发布时间】:2011-09-28 23:56:37
【问题描述】:

这是我到目前为止所得到的。请阅读代码中的注释。它包含我的问题。

var customer;   //global variable
function getCustomerOption(ddId){
      $.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
           $('>option', dd).remove(); // Remove all the previous option of the drop down
           if(opts){  
                customer = jQuery.parseJSON(opts); //Attempt to parse the JSON Object.
           }
      });
}

function getFacilityOption(){
      //How do I display the value of "customer" here. If I use alert(customer), I got null
}

这是我的 json 对象的外观:{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}。我最终想要的是,如果我传入密钥3,我想得到Stanley Furniture,如果我传入Stanley Furniture,我得到一个3。因为3 是我的数据库中的customerId 而Stanley Furniture 是customerName。

【问题讨论】:

    标签: javascript jquery json jsp


    【解决方案1】:

    如果 servlet已经返回 JSON(正如 URL 所暗示的那样),您不需要在 jQuery 的 $.getJSON() 函数中解析它,而只需 handle它作为 JSON。摆脱那个jQuery.parseJSON()。这可能会使事情变得更糟。 getFacilityOption()函数应该作为$.getJSON()的回调函数或者你需要将其逻辑写在function(opts)中(其实就是当前的回调函数)。

    一个JSON字符串

    {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
    

    ...按以下方式访问时会返回“Stanley Furniture”

    var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
    alert(json['3']);
    // or
    var key = '3';
    alert(json[key]);
    

    要了解有关 JSON 的更多信息,我强烈建议您访问this article。要了解有关$.getJSON 的更多信息,请查看its documentation

    【讨论】:

    • 什么? JSON 是 JavaScript 对象的字符串表示形式,因此如果您想将其作为常规对象访问,它确实需要解析...
    • 抱歉,过了一段时间才回复您。我只是想确保我完整地阅读了你寄给我的文章,而且学校在期中期间非常疯狂。但是,我读完之后,我想我解决了我的问题。非常感谢。 :)
    【解决方案2】:

    getJSON 将触发异步 XHR 请求。因为它是异步的,所以不知道它什么时候会完成,这就是为什么你将回调传递给getJSON——这样 jQuery 就可以让你知道它什么时候完成。因此,变量customer 仅在请求完成后才被分配,而不是在之前。

    parseJSON 返回一个 JavaScript 对象:

    var parsed = jQuery.parseJSON('{"foo":"bar"}');
    alert(parsed.foo); // => alerts "bar"
    

    .. 但是,正如 BalusC 所说,您不需要解析任何内容,因为 jQuery 会为您解析,然后将生成的 JS 对象传递给您的回调函数。

    【讨论】:

      【解决方案3】:
      var customer;   //global variable
      function getCustomerOption(ddId){
            $.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
                 $('>option', dd).remove(); // Remove all the previous option of the drop down
                 if(opts){  
                      customer = opts; //Attempt to parse the JSON Object.
                 }
            });
      }
      
      function getFacilityOption(){
        for(key in costumer)
        {
          alert(key + ':' + costumer[key]);   
        }
      }
      

      【讨论】:

      • 我认为您的代码不起作用。对不起。它返回[对象对象]。 :( :(
      • 对不起...现在用 for() 循环试试
      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      • 2015-10-27
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      相关资源
      最近更新 更多