开发者

jQuery Ajax/ASP.NET MVC JsonResult using dynamics, how do I access the JSON keys?

Here's the JSON string returned from my action:

[{"Key":"Likes","Value":1},{"Key":"Loves","Value":0},{"Key":"Dislikes","Value":0},{"Key":"Message","Value":"Your vote has been changed"}]

Here's how I'm trying to access them:

$.ajax({
    type: "POST",
    url: '/voteUrl',
    data: { id : '37', vote : $(this).attr('id') },
    dataType: "json",
    success: function(result) {
        $('#like').text(result.Likes开发者_如何转开发);
        $('#love').text(result.Loves);
        $('#dislike').text(result.Dislikes);
    }
});

There are span tags with id's "Like", "Love", and "Dislike." On the action, there is a dynamic result, with properties like so:

results.Likes = 1;
results.Loves = 0;
results.Dislikes = 0;
results.Message = "Your vote has been changed";

But the span tags aren't being updated with the correct values. The ajax call is working, FireBug shows the JSON string is returned, and I believe I'm trying to access the keys correctly, results.PropertyName. What's missing?


Do something like this

success: function(data) {
    var results = [];
    for(var i=0; i < data.length; i++){    
        results[data[i]["Key"]] = data[i]["Value"];
    }
    $('#like').text(result.Likes);
    $('#love').text(result.Loves);
    $('#dislike').text(result.Dislikes);
}


You are returning an array, so to show all, you have to use for loop. Also in your current code, you are not accessing array by key. The correct code could be:

success: function(result) {
 for(var i=0;i<result.length;i++)
        $('#like').text(result[0].Value); //got likes in first iteration
        ...
}

or if you have fixed length, than get the value directly instead of forloop or by comparing the key if you want to use for loop

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜