javascript - 如何显示 JSON 对象的值?

标签 javascript jquery json jsp

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

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"}。我最终想要的是,如果我传入 key 3,我想取回 Stanley Furniture,如果我传入 Stanley Furniture ,我得到了 3 。因为 3 是我数据库中的 customerId 而 Stanley Furniture 是 customerName。

最佳答案

如果 servlet 已经 返回 JSON(正如 URL 似乎暗示的那样),您不需要在 jQuery 的 $.getJSON() 函数中解析它,但是只需将其作为 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 .

关于javascript - 如何显示 JSON 对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2373524/

相关文章:

javascript - 当页面滚动时隐藏元素,但当页面变为静态时元素再次出现

javascript - 使用基本 URL 和 Javascript 自动生成 YouTube 嵌入内容

java - 使用 Java 在 Jackson 中进行通用对象序列化

javascript - 如何在 phonegap 应用程序中使用存储在 localStorage 中的 json 提要?

json - 更新 mongodb 中的文档

javascript - 降低 if/else 语句的复杂性?

javascript - RowFilter 不匹配时显示消息

JavaScript != =""无法正常工作

javascript -> 高度的平滑滚动效果(视差效果)

javascript - D3.js 高亮相关节点/链接