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

Luc*_*cas 3 ajax jquery json

对不起,我知道这个问题很简单,但我不知道如何从返回的字典中获取响应数据:

这是我的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)
            });
        }
    });
});?
Run Code Online (Sandbox Code Playgroud)

这是警报打印的内容:

{"name": "First Value", "phone": "434534"}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能从字典的'name'键中获取值?

这样data.name的警告内部有没有效果.

谢谢!

ran*_*ame 5

看来你正在返回一个JSON字符串.如果是这种情况,那么首先需要运行jQuery的parseJSON函数:

var d = $.parseJSON(data);
alert(d.name); // Will output the name from the JSON string.
Run Code Online (Sandbox Code Playgroud)

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

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

  • 你也可以使用`$ .getJSON`而不仅仅是`$ .get`,它也会自动调用`$ .parseJSON`. (3认同)