How to extract the contents of "data" and load them inside form inputs ? the situation is like this, I have a data开发者_如何学C displayed, it's being pulled out from a database table. now on that displayed data, I placed an "edit" link. now my problem is, how to use this json thing, in order for me to be able to load the data of the clicked/to be edited data in the input forms ?
$(function() {
//retrieve comments to display on page
$.getJSON("testfile.php?jsoncallback=?", function(data) {
//what to code here?
});
});
Traverse the DOM then Modify the HTML
parse json coming from server using jquery parser and then place data wherever you want
if you have simple field value mapping returned back, following do the trick for you
$.each(data, function(key, val) {
$('#'+key).val(val);
});
Sample data -
{
"name": "name",
"address": "address"
}
but if nested data is returning, you need to traverse you objects.
I name my input fields the same as JSON properties. So if i have the following object:
{
"foo": "",
"bar": {
"baz": ""
}
}
the fields would be defined as:
<input name="foo" class="jsonItem">
<input name="bar.baz" class="jsonItem">
and JSON success handler would fill them recursively:
$.getJSON("testfile.php?jsoncallback=?", function(data) {
function(root) {
var fillInputs = function(obj, prefix) {
prefix = prefix ? prefix + '.' : '';
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var prefixOrName = prefix + prop;
var propVal = obj[prop];
if (typeof propVal === 'object') {
fillInputs(propVal, prefixOrName);
}
else {
$('input.jsonItem[name=' + prefixOrName + ']').val(propVal);
}
}
}
};
fillInputs(root, '');
});
If you want to use the id instead of name, be sure to escape the dots in the selector:
prefix = prefix ? prefix + '\.' : '';
...
$('input.jsonItem#' + prefixOrName).val(propVal);
Also, since I was lazy, the above function does not take into account arrays in the JSON object, but that shouldn't be hard to add.
精彩评论