Reputation: 3435
I can't seem to be able to insert a JSON value into an input element in my markup. Any ides? I did verify that the .ajax call is returning the correct JSON. Its probably something simple, but I just can't seem to get it to work. Thanks!
html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-2.0.3.min.js"></script>
</head>
<body>
<div>
<form>
<fieldset>
<legend>The Person</legend>
<label>Name: </label>
<input id="Name"/>
<label>Age: </label>
<input id="Age" />
</fieldset>
</form>
</div>
<script type="text/javascript" src="~/Scripts/Custom.js"></script>
</body>
</html>
javascript
$(document).ready(function () {
$.ajax({
url: '/Home/GetPerson',
type: 'GET',
success: function (result) {
alert(JSON.stringify(result));
$('#Name').val(result[0].FirstName);
}
});
});
JSON.stringify returns
{"FirstName": "Steve", "LastName": "Smith"}
Upvotes: 0
Views: 140
Reputation: 150020
The JSON is
{"FirstName": "Steve", "LastName": "Smith"}
Remove the [0]
from result[0].FirstName
:
$('#Name').val(result.FirstName);
The [0]
part would only be applicable if result
was an array of objects and you wanted the first item, e.g., if your JSON was something like this:
[{"FirstName": "Steve", "LastName": "Smith"}, {"FirstName": "Mary", "LastName": "Jones"}]
Upvotes: 5