I need to generate json from the serverside, which I know how to do. However, I do not know how to format this json data so it can easily be used in jQuery?
here is the script I have at the moment. What is the best way to format json data so I can fill in 3 input fields?
$('input#btnGet').click(function() {
$.ajax({
url: 'generate_json.aspx',
type: 'POST',
data: { intPageID:1 },
success: function(results) {
$('input#id').v开发者_开发知识库al('id goes here');
$('input#heading').val('heading goes here');
$('input#content').val('content goes here');
}
});
});
If you add dataType: 'json'
to your options, then jQuery directly decodes the JSON into a JavaScript object:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
Assuming the JSON you receive/generate is
'{"id": 6, "heading": "heading", "content": "content"}'
your code would look like this:
$.ajax({
url: 'generate_json.aspx',
type: 'POST',
data: { intPageID:1 },
dataType: 'json',
success: function(results) {
$('#id').val(results.id);
$('#heading').val(results.heading);
$('#content').val(results.content);
}
});
If your JSON string represents an array instead, then of course results
would be a JavaScript array and you have to loop over it.
Btw. as IDs are unique, there is not need to prepend the tag name in the selector.
Just specify dataType as "json" and you're set!
$.ajax({
url: 'generate_json.aspx',
type: 'POST',
data: { intPageID:1 },
dataType: "json",
success: function(result){$("#heading").val(result.heading)}
});
If you server returns this:
{
"id": "1",
"heading": "yadayada"
"content": "foobar"
}
You can use it like:
success: function(results) {
$('input#id').val(results.id);
$('input#heading').val(results.heading);
$('input#content').val(results.content);
}
精彩评论