I have a controller method GetNearbyUsers which returns a list of users as a JsonResult. I am trying to call the method using the following ajax function:
function getNearbyUsers(interest) {
$.ajax(
{
type: "POST",
url: "/Interest/GetNearbyUsers",
data: { "interest": interest},
success:
function (result) {
console.log(result);
for (var item in result) {
console.log(item.username);
}
},
error: function (req, status, error) {
window.alert("Error!");
}
});
}
At the moment I'm just trying to display the usernames in the console to make sure it is working and I will move on from their. The controller method works fine and returns the correct JsonResult; in fact printing 'result' gives:
[Object, Object, Object, Object, Object]
0: Object
Id: Object
Interests: Array[3]
LastUpdated: "/Date(1367419763994)/"
Location: Array[2]
Password: "password"
UserName: "user1"
__proto__: Object
1: Object
2: Object
3: Object
4: Object
So the Ajax call seems to be working and getting the right data. However, when I try accessing the objects in the list e.g. item.username, it tells me that username is undefined. When I just do console.log(item) it just prints the index. I also tried using JSON.parse on 'result' but it gives me the 'Unexpected token o' error. Any ideas?