我无法从jQuery.get()返回的字典中获取特定值

时间:2012-07-03 00:05:47

标签: ajax json jquery

抱歉,我知道这个问题很简单,但我不知道如何获取响应数据 来自返回的字典:

这是我的jQuery.get()方法:

$("#selectDireccion").change(function() {
    $("select option:selected").each(function() {
        if ($(this).index() != 0) {
            valorKeyId = $(this).val()
            $.get("/ajaxRequest?opcion=obtenerSedeKeyId", {
                keyId: valorKeyId
            }, function(data) {
                alert(data)
            });
        }
    });
});​

这是警告打印的内容:

{"name": "First Value", "phone": "434534"}

如何从字典的'name'键中获取值?

在警报内执行data.name无效。

谢谢!

1 个答案:

答案 0 :(得分:5)

您似乎正在返回JSON字符串。如果是这种情况,那么首先需要运行jQuery' parseJSON函数:

var d = $.parseJSON(data);
alert(d.name); // Will output the name from the JSON string.

或者,更好(根据@calvin L的评论),使用jQuery getJSON开头:

$.getJSON("/ajaxRequest?opcion=obtenerSedeKeyId",{keyId:valorKeyId}, function(data){
    alert(data.name); // Data already parsed to JSON, outputs the name
});