Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

javascript - How to parse this PHP generated object

Here is some PHP code that generates a json (javascript) object in response to a web service requestion. I'm not sure how to iterate over this object. I've looked at a lot of examples and they are in jQuery and don't deal the case (as mine does) of having sub-objects which I need to render in my select object.

Can anyone show me how to use a javascript object like this to populate a select list?

There are also sub objects with value indexs

data = object(
    0 => object(
        'label' = > 'test1',
        'value' = > 1
    ),
    1 => object(
        'label' = > 'test1',
        'value' = >
        0 = > object(
            'label' = > 'sub testing1',
            'value' = > 1
        ),
        1 = > object(
            'label' = > 'sub testing2',
            'value' = > 1
        ),
    ),
    3 = > object(
        'label' = > 'test3',
        'value' = >
        0 = > object(
            'label' = > 'sub testing - test 3',
            'value' = > 33
        ),
    )
)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once you have the php data transformed into JSON format, you can use the resulting object to generate a drop down. The best way to my mind to do this with PrototypeJS is to convert it into a hash.

$H(obj);

A hash can be easily used by iterating through the key-value pairs like so:

var selectOpts = new String();
$H(obj).each(function(pair){
    selectOpts += "<option value="" + pair.key + "">" + pair.value + "</option>";
});

The above is assuming the key is the actual value while value is the "label". With your dataset you might want to obtain the value object and access the label and value with dotr notation.

If you are using Script.aculo.us, then you might considering creating the HTML options using the module Builder:

selectOpt = Builder.node("option", { [attribs] });

In that case you'need to array push the "built" option nodes and append it inside a select element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...