以优雅的方式将响应文本解析为键值对

时间:2014-12-19 12:51:21

标签: javascript c# jquery ajax json

似乎无法在搜索中找到我正在寻找的东西,所以这可能是重复的但是我还没有找到原创的东西......

我有一个ajax电话:

$.ajax({
    url: "/events/instructor/",
    type: 'POST',
    data: {
        instructorID: $(this).attr("id")
    },
    complete: function (data) {
        $("#name").html(data["responseText"]["name"]);
        $("#email").html(data["responseText"]["email"]);
        $("#photo").html(data["responseText"]["photo"]);
        $("#summary").html(data["responseText"]["summary"]);
        $("#url").html(data["responseText"]["url"]);
    }
});

返回的数据由服务器(C#)以JSON编码。

显然,data["responseText"]["fieldName"]没有做到这一点。我可以做拆分等等但这意味着如果格式发生变化,我需要确保上面的代码跟上数据的变化形状。

我怎样才能说出像data["responseText']["fieldName"]那样简单的东西来获取该密钥的价值?

2 个答案:

答案 0 :(得分:1)

我认为你需要先解析json。看看api.jquery.com/jquery.parsejson

// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"

P.S。也可以更好地使用'成功'代替'完成',你可以在这里阅读Difference between .success() and .complete()?

success: function(data) {
  console.log("response is good", data);
},
error: function (){
  console.log("something is went wrong");
}

答案 1 :(得分:0)

尝试使用这样:

complete: function (data) {
        var data=JSON.parse(data);
         $("#name").html(data.responseText.name);
        $("#email").html(data.responseText.email);
        $("#photo").html(data.responseText.photo);
        $("#summary").html(data.responseText.summary);
        $("#url").html(data.responseText.url);     

    }

只获得正确的响应使用成功。