开发者

how to extract data from getJson?

开发者 https://www.devze.com 2023-04-09 03:15 出处:网络
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

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.

0

精彩评论

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